package com.ytjj.qmyx.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.db.PageResult;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.util.StringUtil;
import com.google.common.collect.Lists;
import com.ytjj.common.api.CommonPage;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.constants.CopyWriterConstant;
import com.ytjj.common.constants.QueueConstants;
import com.ytjj.common.dto.mqdto.SmsDto;
import com.ytjj.common.enums.NeedPhoneExpressEnum;
import com.ytjj.common.enums.PaySourceEnum;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.service.AlipayService;
import com.ytjj.common.service.RedisService;
import com.ytjj.common.utils.CopyWriterConfigUtil;
import com.ytjj.common.utils.HttpClientUtil;
import com.ytjj.common.utils.OrderUtils;
import com.ytjj.common.utils.feishu.FeiShuUtil;
import com.ytjj.qmyx.admin.config.SupplyApiConfig;
import com.ytjj.qmyx.admin.dao.BankerDao;
import com.ytjj.qmyx.admin.dao.OrdersDao;
import com.ytjj.qmyx.admin.dao.ReturnGoodsDao;
import com.ytjj.qmyx.admin.dao.ReturnRegisterDao;
import com.ytjj.qmyx.admin.eunm.ModuleEnum;
import com.ytjj.qmyx.admin.eunm.OrderStatusEnums;
import com.ytjj.qmyx.admin.eunm.ReasonTypeEnums;
import com.ytjj.qmyx.admin.eunm.ReturnGoodsStatusEnums;
import com.ytjj.qmyx.admin.mapper.OrderDisparitiesRefundMapper;
import com.ytjj.qmyx.admin.mapper.OrdersForbidMapper;
import com.ytjj.qmyx.admin.mapper.ReturnDutyMapper;
import com.ytjj.qmyx.admin.model.*;
import com.ytjj.qmyx.admin.model.dto.ReturnDutyDto;
import com.ytjj.qmyx.admin.model.request.*;
import com.ytjj.qmyx.admin.model.request.channel.ChannelReturnGoodsRequest;
import com.ytjj.qmyx.admin.model.response.*;
import com.ytjj.qmyx.admin.model.vo.GoodReturnInfoVO;
import com.ytjj.qmyx.admin.service.*;
import com.ytjj.qmyx.admin.utils.ExpressDicUtil;
import com.ytjj.qmyx.admin.utils.UserUtil;
import com.ytjj.qmyx.mall.client.MallClient;
import com.ytjj.qmyx.mall.mapper.*;
import com.ytjj.qmyx.mall.model.BankerRequest;
import com.ytjj.qmyx.mall.model.BankerResponse;
import com.ytjj.qmyx.mall.model.*;
import com.ytjj.qmyx.mall.model.YxReturnGoods;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.projection.Accessor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 *
 *
 * @Version: 1.0
 */
@Service
@Slf4j
@RefreshScope
public class ReturnGoodsServiceImpl implements ReturnGoodsService {

	@Resource
	private ReturnGoodsDao returnGoodsDao;

	@Resource
	private MemberService memberService;

	@Resource
	private OrdersInfoMapper ordersInfoMapper;

	@Resource
	private OrdersMapper ordersMapper;

	@Resource
	private CopyWriterConfigUtil copyWriterConfigUtil;

	@Resource
	private OrdersRefundMapper refundMapper;

	@Resource
	private OrdersDao ordersDao;

	@Resource
	private AlipayService alipayService;

	@Resource
	private ReturnRegisterDao returnRegisterDao;

	@Resource
	private MallClient mallClient;

	@Resource
	private BankerDao bankerDao;

	@Resource
	private RedissonClient redissonClient;

	@Resource
	private ProductMapper productMapper;

	@Resource
	private SupplyApiConfig supplyApiConfig;

	@Resource
	private RedisService redisService;
	@Resource
	private ReturnGoodsMapper returnGoodsMapper;

	@Autowired
	private OrderNoteService orderNoteService;
	@Resource
	private ReturnRegisterMapper returnRegisterMapper;

	@Lazy
	@Autowired
	private ReturnDutyService returnDutyService;

	@Resource
	private ReturnDutyMapper returnDutyMapper;
	@Resource
	private AdminModuleLogService adminModuleLogService;

	@Autowired
	private AdminService adminService;

	@Resource
	private OrdersPayMapper ordersPayMapper;
	@Resource
	private OrdersForbidMapper ordersForbidMapper;
	@Resource
	private OrderDisparitiesRefundMapper orderDisparitiesRefundMapper;
	@Resource(name = "guchuangRabbitTemplate")
	private RabbitTemplate guchuangRabbitTemplate;
//	@Resource(name = "jumaiduoRabbitTemplate")
//	private RabbitTemplate jumaiduoRabbitTemplate;
//	@Resource(name = "yiquanRabbitTemplate")
//	private RabbitTemplate yiquanRabbitTemplate;
//	@Resource(name = "zxlpRabbitTemplate")
//	private RabbitTemplate zxlpRabbitTemplate;
//	@Resource(name = "ygyxRabbitTemplate")
//	private RabbitTemplate ygyxRabbitTemplate;
//	@Resource(name = "yxhdRabbitTemplate")
//	private RabbitTemplate yxhdRabbitTemplate;
//	@Resource(name = "jckjRabbitTemplate")
//	private RabbitTemplate jckjRabbitTemplate;

	@Value("${returnGood.auditSuccessContent:您的售后申请已审核通过,请重新进入售后订单页面(uqt3.cn/5XVri),按对应的退货地址安排快递寄回商品,并须在七天内上传正确的退货快递单号（运单号）及对应物流公司,以便系统自动进入退款流程,超时售后申请将会关闭！如有疑问，可咨询商城人工在线客服！}")
	private String auditSuccessContent;
	@Value("${returnGood.auditFailContent:您的售后申请审核失败,（失败原因:%s）,如有需要,请按相关要求重新提交(uqt3.cn/5XVri);如有疑问,可咨询商城人工在线客服!}")
	private String auditFailContent;

	/**
	 * 受限制角色id(订单金额)
	 */
	@Value("${limit.userPhone.roleId:10,71,1}")
	private String limitUserPhoneRoleId;

	@Override
	public CommonPage<ReturnGoodsResponse> selectList(ReturnGoodsRequest request) {

		List<Integer> bankerIdLists = new ArrayList<>();
		if (org.apache.commons.lang3.StringUtils.isNotBlank(request.getBuyer())){
			BankerRequest request1 = new BankerRequest();
			request1.setBuyer(request.getBuyer());
			String json1 = com.alibaba.fastjson.JSON.toJSONString(request1);
			String result = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/banker/getBankerIdsByBankerMsg", json1, supplyApiConfig.getHeadsMap());
			List<Integer> bankerIds = com.alibaba.fastjson.JSONObject.parseArray(result, Integer.class);
			if (CollectionUtils.isEmpty(bankerIds)){
				return CommonPage.restPage(new ArrayList<>());
			}
			bankerIdLists.addAll(bankerIds);
		}

		//判断供应商名称是否为空
		if (org.apache.commons.lang3.StringUtils.isNotBlank(request.getBankerName())){
			//调用API查询该供应商的供应商id
			Map<String, String> paramMap = new HashMap<>();
			paramMap.put("bankerName", request.getBankerName());
			String result = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/banker/getBankerIdByBankerName", paramMap, supplyApiConfig.getHeadsMap());
			List<Integer> bankerIds = JSONObject.parseArray(result, Integer.class);
			if (CollectionUtils.isEmpty(bankerIds)){
				return CommonPage.restPage(new ArrayList<>());
			}
			bankerIdLists.addAll(bankerIds);
		}
		if (!CollectionUtils.isEmpty(bankerIdLists)){
			request.setBankerIds(bankerIdLists);
		}

		PageHelper.startPage(request.getPageNum(), request.getPageSize());
		List<ReturnGoodsResponse> pageList = returnGoodsDao.selectList(request);
		if (CollectionUtils.isEmpty(pageList)){
			return CommonPage.restPage(new ArrayList<>());
		}

		boolean checkUserPhoneFlag = checkUserPhoneIsLimitRole();
		List<Integer> bankerIdList = pageList.stream().filter(item -> null != item.getBankerId()).map(ReturnGoodsResponse::getBankerId).collect(Collectors.toList());

//		List<Integer> productIdList = pageList.stream().filter(item -> null != item.getProductId()).map(ReturnGoodsResponse::getProductId).collect(Collectors.toList());
//		ProductExample example = new ProductExample();
//		example.createCriteria().andIdIn(productIdList);
//		List<Product> products = productMapper.selectByExample(example);

		List<BankerResponse> bankerResponses = getBankerMsg(bankerIdList);//供应商信息
		String bankerIds = bankerIdList.stream().map(item -> String.valueOf(item)).collect(Collectors.joining(","));
		List<BankerStoreAddressResponse> bankerStoreAddressResponses = newGetReturnAddressByBankerId(bankerIds);

		List<String> childOrderNoList = pageList.stream().filter(item -> null != item.getChildOrderNo()).map(ReturnGoodsResponse::getChildOrderNo).collect(Collectors.toList());
		List<OrdersInfoFreightDto> ordersInfoFreightList = ordersDao.selectFreightByChildOrderNoList(childOrderNoList);
		List<String> tradeNos = pageList.stream().map(ReturnGoodsResponse::getTradeNo).collect(Collectors.toList());
		List<OrdersPay> ordersPays = ordersDao.queryOrdersPays(tradeNos);
		pageList.stream().forEach(item -> {
			List<OrdersInfoFreightDto> OrdersInfoFreightDto = ordersInfoFreightList.stream().filter(response -> response.getChildOrderNo().equals(item.getChildOrderNo())).collect(Collectors.toList());
			if (!CollectionUtils.isEmpty(OrdersInfoFreightDto)){
				item.setFreight(OrdersInfoFreightDto.get(0).getFreight());
			}

			List<BankerResponse> collect = bankerResponses.stream().filter(response -> response.getBankerId().equals(item.getBankerId())).collect(Collectors.toList());
			if (!CollectionUtils.isEmpty(collect)){
				item.setBankerName(collect.get(0).getBankerName());
				item.setBuyer(collect.get(0).getBuyer());
			}

			if (item.getIsRefund()!=null && item.getIsRefund()==1) {
				item.setRefundStatus("已退款");
			} else {
				item.setRefundStatus("未退款");
			}
			if (item.getReturnDutyId()!=null){
				item.setReturnDutyFlag("已登记");
			} else {
				item.setReturnDutyFlag("未登记");
			}
			//供应链商品id
//			if (!com.alibaba.excel.util.CollectionUtils.isEmpty(products)) {
//				List<Product> collect1 = products.stream().filter(product -> product.getId().equals(item.getProductId())).collect(Collectors.toList());
//				item.setSupplyProductId(com.alibaba.excel.util.CollectionUtils.isEmpty(collect1) ? 0 : collect1.get(0).getSupplyProductId());
//			}

			if (!CollectionUtils.isEmpty(bankerStoreAddressResponses)) {
				List<BankerStoreAddressResponse> collect1 = bankerStoreAddressResponses.stream().filter(res -> res.getBankerId().equals(item.getBankerId())).collect(Collectors.toList());
				item.setReturnTel(com.alibaba.excel.util.CollectionUtils.isEmpty(collect1) ? "" : collect1.get(0).getTel());
			}
			//快递信息
			item.setExpressCompanyNo(item.getExpressCompany());
			item.setExpressCompany(ExpressDicUtil.getKey(item.getExpressCompany()));
			item.setExpressNo(item.getExpressNo());
			item.setReturnExpressCompanyNo(item.getReturnExpressCompany());
			item.setReturnExpressCompany(ExpressDicUtil.getKey(item.getReturnExpressCompany()));
			item.setReturnExpressNo(item.getReturnExpressNo());
			//客户发起的售后，显示客户的备注。客服发起的，显示售后责任中的具体原因
			String remark = "";
			if(item.getServiceCheckIn() == 1 && !StringUtils.isEmpty(item.getReasonDetail()) ){
				remark = item.getReasonDetail();
			}else{
				remark = item.getUserRemarks();
			}
			item.setUserRemarks(remark);
			//设置订单销售渠道
			item.setPlatformInfo(item.getOrderSource() + (org.apache.commons.lang3.StringUtils.isNotBlank(item.getDomainUrl()) ? "_非支付宝" : "_支付宝渠道"));
			//手机号脱敏
			if (org.apache.commons.lang3.StringUtils.isNotBlank(item.getUserPhone())){
				item.setUserPhone(checkUserPhoneFlag ? item.getUserPhone() : item.getUserPhone().replaceAll("(\\w{3})\\w*(\\w{4})", "$1****$2"));
			}

			//支付方式
			if(!CollectionUtils.isEmpty(ordersPays)){
				Optional<OrdersPay> first = ordersPays.stream().filter(e -> e.getResOrderNo().equals(item.getTradeNo())).findFirst();
				String payName = PaySourceEnum.getPayType(first.isPresent() ? first.get().getTradeType() : "");
				item.setPaySource(payName);
			}
		});

		return CommonPage.restPage(pageList);
	}

	public List<BankerResponse> getBankerMsg(List<Integer> bankerIdList) {
		BankerRequest bankerRequest = new BankerRequest();
		bankerRequest.setBankerIdList(bankerIdList);
		String json = JSON.toJSONString(bankerRequest);
		String result = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/product/getBankerMsg", json, supplyApiConfig.getHeadsMap());
		return JSONObject.parseArray(result, BankerResponse.class);
	}

	@Override
	public CommonPage<ReturnGoodsResponse> selectReturnList(ReturnGoodsRequest request) {
		PageHelper.startPage(request.getPageNum(), request.getPageSize());

		ChannelReturnGoodsRequest channelReturnGoodsRequest = new ChannelReturnGoodsRequest();
		BeanUtils.copyProperties(request, channelReturnGoodsRequest);
		String json = JSON.toJSONString(channelReturnGoodsRequest);
		String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/returnGoods/selectReturnGoodsList", json, supplyApiConfig.getHeadsMap());
		CommonPage commonPage = JSONObject.parseObject(resultJson, CommonPage.class);
		List<ReturnGoodsResponse> pageList = JSONArray.parseArray(JSONObject.toJSONString(commonPage.getList()), ReturnGoodsResponse.class);
//		pageList.stream().filter(s -> null != s.getOrdersInfoId()).collect(Collectors.toList()).forEach(item -> {
//			OrdersInfo ordersInfo = ordersInfoMapper.selectByPrimaryKey(item.getOrdersInfoId());
//			if (null == ordersInfo) {
//				return;
//			}
//			if (null != ordersInfo.getOrderId()) {
//				Orders orders = ordersMapper.selectByPrimaryKey(ordersInfo.getOrderId());
//				item.setUserName(orders.getUserName());
//				item.setOrderSource(orders.getOrderSource());
//				item.setOrderNo(orders.getOrderNo());
//				item.setTel(orders.getTel());
//				item.setUserPhone(orders.getUserPhone());
//			}
//			//是否发货
//			if (!StringUtils.isEmpty(ordersInfo.getExpressNo())) {
//				item.setDeliverStatus(1);
//			} else {
//				item.setDeliverStatus(0);
//			}
//			item.setProductSum(ordersInfo.getProductSum());
//			item.setTotalCostPrice(ordersInfo.getCostPrice().multiply(BigDecimal.valueOf(ordersInfo.getProductSum())) );
//			item.setProductSkuSpec(ordersInfo.getProductSkuSpec());
//			item.setOrderStatus(ordersInfo.getOrderinfoStatus());
//			item.setPayPrice(ordersInfo.getPayPrice());
//			item.setBankerId(ordersInfo.getBankerId());
//			item.setChildOrderNo(ordersInfo.getChildOrderNo());
//			item.setOrderTimed(ordersInfo.getCreateTime());
//			item.setProductName(ordersInfo.getProductName());
//			item.setProductImg(ordersInfo.getProductImg());
//			item.setRefundStatus(9 == item.getStatus() ? "已退款" : "未退款");
//			List<ReturnRegister> returnRegisters = returnRegisterDao.selectByOrderInfoId(Arrays.asList(item.getOrdersInfoId()));
//			if(!CollectionUtils.isEmpty(returnRegisters)){
//				item.setRefundTime(Optional.ofNullable(returnRegisters.get(0)).orElse(new ReturnRegister()).getRefundTime());
//			}
//		});
		commonPage.setList(pageList);
		return commonPage;
	}

//	@Override
//	public CommonPage<ReturnGoodsResponse> getReturnData(ChannelReturnGoodsRequest request) {
//		List<ReturnGoodsResponse> result = new ArrayList<>();
//		int pageStart = 1;
//		request.setPageSize(10000);
//		//分多次请求
//		while (true){
//			request.setPageNum(pageStart++);
//			String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/returnGoods/selectReturnGoodsList", JSON.toJSONString(request), supplyApiConfig.getHeadsMap());
//			List list = JSONObject.parseObject(resultJson, CommonPage.class).getList();
//			if(CollectionUtils.isEmpty(list)){
//				break;
//			}
//			List<ReturnGoodsResponse> pageList = JSONArray.parseArray(JSONObject.toJSONString(list), ReturnGoodsResponse.class);
//			Map<Integer, List<ReturnGoodsResponse>> collect = pageList.stream().collect(Collectors.groupingBy(e -> e.getOrdersInfoId()));
//			Set<Integer> ordInfoIds = collect.keySet();
//			pageList.stream().filter(s -> null != s.getOrdersInfoId()).collect(Collectors.toList()).forEach(item -> {
//				OrdersInfo ordersInfo = ordersInfoMapper.selectByPrimaryKey(item.getOrdersInfoId());
//				if (null == ordersInfo) {
//					return;
//				}
//				if (null != ordersInfo.getOrderId()) {
//					Orders orders = ordersMapper.selectByPrimaryKey(ordersInfo.getOrderId());
//					item.setUserName(orders.getUserName());
//					item.setOrderSource(orders.getOrderSource());
//					item.setOrderNo(orders.getOrderNo());
//					item.setTel(orders.getTel());
//					item.setUserPhone(orders.getUserPhone());
//
//					ReturnRegisterExample returnRegisterExample = new ReturnRegisterExample();
//					returnRegisterExample.createCriteria().andOrderInfoIdEqualTo(ordersInfo.getId()).andStatusEqualTo(0);
//					List<ReturnRegister> returnRegisters = returnRegisterMapper.selectByExample(returnRegisterExample);
//					if(returnRegisters.size() > 0){
//						ReturnRegister returnRegister = returnRegisters.get(0);
//						item.setRefundTime(returnRegister.getRefundTime());
//					}
//				}
//
//				item.setOrderStatus(ordersInfo.getOrderinfoStatus());
//				item.setPayPrice(ordersInfo.getPayPrice());
//				item.setBankerId(ordersInfo.getBankerId());
//				item.setChildOrderNo(ordersInfo.getChildOrderNo());
//				item.setOrderTimed(ordersInfo.getCreateTime());
//				item.setProductName(ordersInfo.getProductName());
//				item.setProductImg(ordersInfo.getProductImg());
//			});
//
//			pageList.stream().forEach(item -> {
//				item.setRefundStatus(9 == item.getStatus() ? "已退款" : "未退款");
//			});
//			result.addAll(pageList);
//		}
//
//		CommonPage commonPage = new CommonPage();
//		commonPage.set
//		return null;
//	}

	@Override
	public CommonResult<ReturnGoodsDetail> getReturnGoodsDetailInfo(Integer id) {
		ReturnGoodsDetail returnGoodsDetail = new ReturnGoodsDetail();

		// 商品信息
		ReturnProductDetail productInfo = returnGoodsDao.getProductInfo(id);

		List<Integer> bankerIdList = new ArrayList<>();
		bankerIdList.add(productInfo.getBankerId());
		List<BankerResponse> bankerResponses = getBankerMsg(bankerIdList);
		if (!CollectionUtils.isEmpty(bankerResponses)){
			productInfo.setBankerName(bankerResponses.get(0).getBankerName());//供应商名称
		}
		productInfo.setPrice(returnGoodsDao.getSpecPrice(productInfo.getProductId(), productInfo.getSpec()));
		returnGoodsDetail.setReturnProductDetail(productInfo);

		// 物流信息
		ReturnOrdersDetail ordersInfo = returnGoodsDao.getOrdersInfo(id);
		if (StringUtil.isNotEmpty(ordersInfo.getChildOrderNo())){
			ordersInfo.setOrderNo(ordersInfo.getChildOrderNo());
		}
		returnGoodsDetail.setReturnOrdersDetail(ordersInfo);

		// 服务信息
		ReturnServiceDetail serviceInfo = returnGoodsDao.getServiceInfo(id);
		//退货凭证
		if (null != serviceInfo.getUsersRemarksImg()){
			//判断是否为视频
			String[] suffixs = serviceInfo.getUsersRemarksImg().split("\\.");
			if (null != suffixs && suffixs.length > 1) {
				String suffix = suffixs[suffixs.length - 1];
				String s = "avi、mov、rmvb、rm、flv、mp4、3gp";
				boolean contains = s.contains(suffix.toLowerCase());
				serviceInfo.setVideo(contains);
			}
		}

		returnGoodsDetail.setReturnServiceDetail(serviceInfo);

		// 返商信息
		returnGoodsDetail.setReturnBankerDetail(returnGoodsDao.getBankerInfo(id));

		// 上侧时间线
		returnGoodsDetail.setReturnGoodsTime(returnGoodsDao.getExpressInfo(id));

		//判断该商品是否已发货
		boolean flag = false;
		if (!StringUtils.isEmpty(serviceInfo.getOrderInfoId())){
			if (null != ordersInfo && !StringUtils.isEmpty(ordersInfo.getExpressNo())) {
				flag = true;
			}
		}
		returnGoodsDetail.setDeliverFlag(flag);
		//售后流程优化
		returnGoodsDetail.setIsRefund(ordersInfo.getIsRefund());
		//查询是否同步到原路返回页
		ReturnRegisterExample example = new ReturnRegisterExample();
		example.createCriteria().andOrderInfoIdEqualTo(ordersInfo.getOrdersInfoId()).andStatusEqualTo(0);
		List<ReturnRegister> returnRegisters = returnRegisterMapper.selectByExample(example);
		returnGoodsDetail.setReturnRegisterNum(Long.valueOf(returnRegisters.size()));
		if(returnRegisters.size() > 0){
			returnGoodsDetail.setOperationName(returnRegisters.stream().map(e->e.getOperationName()).collect(Collectors.joining(",")));
			returnGoodsDetail.setReturnRegisterTime(returnRegisters.get(0).getCreateTime());
		}
		return CommonResult.success(returnGoodsDetail);
	}

	@Override
	public CommonResult<ReturnGoodsDetail> getReturnGoodsDetailInfoBySupplyChain(Integer id) {
		Map<String, String> param = new HashMap<String, String>();
		param.put("id", String.valueOf(id));
		String jsonStr = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/returnGoods/getDetailById", param, supplyApiConfig.getHeadsMap());

		CommonResult commonResult = JSONObject.parseObject(jsonStr, CommonResult.class);
		if (200 != commonResult.getCode()) {
			throw new ApiException("获取数据失败，请稍后重试");
		}
		return commonResult;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public CommonResult auditSuccess(Integer id) {
		Admin admin = memberService.getAdmin();
		ReturnGoods returnGood = returnGoodsMapper.selectByPrimaryKey(id);
		if (returnGood.getAfterType().equals(1) && returnGood.getBankerStatus().equals(1)){
			throw new ApiException("该售后类型为退款,供应商审核后,客服才能审核");
		}
		if (returnGood.getAfterType().equals(2) &&
				(StringUtils.isEmpty(returnGood.getReturnExpressNo()) || StringUtils.isEmpty(returnGood.getReturnExpressCompany())) &&
				returnGood.getStatus() == 2){
			throw new ApiException("该售后类型为退货退款时,返商信息的物流公司和物流单号不能为空。");
		}
		if (returnGood.getStatus() == 1 && null != returnGood.getAfterType()) {
			//如果售后类型为退款,仅退款
			YxReturnGoods yxReturnGoodsRequest = new YxReturnGoods();//供应链参数
			returnGood.setAfterSalesPassTime(new Date());
			returnGood.setAfterSalesPassUser(admin.getId());
			if ((returnGood.getAfterType() == 1 && returnGood.getBankerStatus() != 1) || returnGood.getAfterType() == 3){
				returnGood.setServiceStatus(2);
				returnGood.setStatus(4);
			}else if (returnGood.getAfterType() == 2){//如果售后类型为退货退款
				//修改状态为审核通过
				returnGood.setServiceStatus(2);
				returnGood.setStatus(2);
			}
			//是否已填写售后订单责任
			ReturnDutyExample example = new ReturnDutyExample();
			example.createCriteria().andServiceNoEqualTo(returnGood.getServiceNo()).andDelFlagEqualTo(0);
			example.setOrderByClause("id desc");
			List<ReturnDuty> returnDuties = returnDutyMapper.selectByExample(example);
			if (CollectionUtils.isEmpty(returnDuties)) {
				throw new ApiException("请先填写售后订单责任！");
			}
			returnGood.setServiceApplyId(admin.getId());
			returnGood.setServiceApplyName(admin.getName());
			returnGood.setServiceApplyTime(new Date());
			//修改客服审核状态为同意
			log.debug("=======修改销售端退货信息====客服同意====参数:{}",JSONObject.toJSONString(returnGood));
			int count = returnGoodsMapper.updateByPrimaryKeySelective(returnGood);

			//发送审核成功短信
			try{
				if (returnGood.getAfterType().equals(2) ) {
					Orders orders = ordersDao.getOrdersByOrderInfoId(returnGood.getOrdersInfoId());
					if (!StringUtils.isEmpty(orders.getTel())) {
						SmsDto dto = new SmsDto();
						dto.setType(10);
						dto.setPhone(orders.getTel());
						dto.setCode(auditSuccessContent);
						String shopId = supplyApiConfig.getShopId();
						if ("GUOB004".equals(shopId) || "GUOB005".equals(shopId) || "GUOB006".equals(shopId) || "GUOB007".equals(shopId)) {
							guchuangRabbitTemplate.convertAndSend(QueueConstants.SMS_QUEUE, dto);
						}
//						else if ("JUMD005".equals(shopId) || "JUMD006".equals(shopId) || "JUMD007".equals(shopId)|| "JUMD008".equals(shopId)) {
//							jumaiduoRabbitTemplate.convertAndSend(QueueConstants.SMS_QUEUE, dto);
//						} else if ("YQKJ006".equals(shopId) || "YQKJ007".equals(shopId) || "YQKJ008".equals(shopId) || "YQKJ009".equals(shopId)) {
//							yiquanRabbitTemplate.convertAndSend(QueueConstants.SMS_QUEUE, dto);
//						} else if ("ZXLP005".equals(shopId) || "ZXLP006".equals(shopId) || "ZXLP007".equals(shopId) || "YQKJ008".equals(id) ) {
//							zxlpRabbitTemplate.convertAndSend(QueueConstants.SMS_QUEUE, dto);
//						} else if ("YGYX006".equals(shopId) || "YGYX007".equals(shopId) || "YGYX008".equals(shopId) || "YGYX005".equals(id) ) {
//						    ygyxRabbitTemplate.convertAndSend(QueueConstants.SMS_QUEUE, dto);
//						} else if ("YXHD006".equals(shopId) || "YXHD007".equals(shopId) || "YXHD008".equals(shopId) || "YXHD005".equals(id) ) {
//							yxhdRabbitTemplate.convertAndSend(QueueConstants.SMS_QUEUE, dto);
//						} else if ("JCYX006".equals(shopId) || "JCYX007".equals(shopId) || "YGYX008".equals(shopId) || "YGYX005".equals(id) ) {
//							jckjRabbitTemplate.convertAndSend(QueueConstants.SMS_QUEUE, dto);
//						}
					} else {
						log.error("发送审核成功短信失败原因为订单的用户手机号码为空!");
					}
				}
			}catch (Exception e) {
				log.error("发送审核成功短信失败:{}",e);
			}

			yxReturnGoodsRequest.setServiceNo(returnGood.getServiceNo());
			yxReturnGoodsRequest.setServiceStatus(returnGood.getServiceStatus());
			yxReturnGoodsRequest.setServiceApplyTime(returnGood.getServiceApplyTime());
			yxReturnGoodsRequest.setStatus(returnGood.getStatus());
			String result = updateReturnGoods(yxReturnGoodsRequest);
			CommonResult commonResult = JSONObject.parseObject(result, CommonResult.class);
			if (null == commonResult || 200 != commonResult.getCode()) {
				return CommonResult.failed();
			}
			return CommonResult.success(count);
		}
		throw new ApiException("提示：状态为退货中/审核中的数据，才允许进行审核操作！");
	}

	@Override
	public void insertAddress(BankerAddressRequest request) {
		Admin admin = memberService.getAdmin();
		ReturnGoods returnGoods = returnGoodsMapper.selectByPrimaryKey(request.getReturnGoodsId());
		//快递信息不能为空
		if (StringUtils.isEmpty(request.getReturnExpressCompany()) || StringUtils.isEmpty(request.getReturnExpressNo())) {
			throw new ApiException("快递信息请填写完整！");
		} else if (null != NeedPhoneExpressEnum.getExpressName(request.getReturnExpressCompany())) {//特别的快递公司判断
			if (StringUtils.isEmpty(request.getRelatedPhone())) {
				throw new ApiException("寄件人手机号为必填项！");
			}
		} else if (!StringUtils.isEmpty(request.getReturnExpressCompany()) && !StringUtils.isEmpty(request.getReturnExpressNo())) {
			OrdersInfo ordersInfo = ordersInfoMapper.selectByPrimaryKey(returnGoods.getOrdersInfoId());
			if (request.getReturnExpressCompany().equals(ordersInfo.getExpressCompanyNo()) && request.getReturnExpressNo().equals(ordersInfo.getExpressNo())) {
				throw new ApiException("寄回单号不能和发货单号一致！");
			}
		}
		if (returnGoods.getAfterType() == 3) {
			if (!StringUtils.isEmpty(request.getReturnExpressNo()) || !StringUtils.isEmpty(request.getReturnExpressCompany())) {
				throw new ApiException("当前售后类型为仅退款，无需填写寄回单号！");
			}
		}
		request.setStatus(returnGoods.getStatus());
//		request.setStatus(8);
		String addressId = "";
		if (request.getNewAddress() == 0) {
			if (null == request.getName()){
				throw new ApiException("收货人姓名不能为空");
			}
			if (null == request.getProvinceId() || null == request.getCityId()){
				throw new ApiException("省市不能为空");
			}
			if (null == request.getTel()){
				throw new ApiException("收货人电话不能为空");
			}
			if (null == request.getAddress()){
				throw new ApiException("详细地址不能为空");
			}
			//插入到供应商的地址管理中
			request.setRemark("平台添加地址");

			try {
				BankerStoreAddressResponse bankerStoreAddressResponse = new BankerStoreAddressResponse();
				BeanUtils.copyProperties(request,bankerStoreAddressResponse);
				String json = JSON.toJSONString(bankerStoreAddressResponse);
				addressId = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/returnGoods/insertAddress", json, supplyApiConfig.getHeadsMap());
			} catch (BeansException e) {
				log.error("====生成新售后地址异常===={}",e);
			}

			//获取供应商商品id
			Product pro = productMapper.selectByPrimaryKey(request.getProductId());
			//修改地址id到供应商商品表
			try {
				Map<String,String> map = new HashMap<>();
				map.put("bankerProductId",pro.getBankerProductId().toString());
				map.put("addressId",addressId);
				HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/returnGoods/updateBankerProductAddressId", map, supplyApiConfig.getHeadsMap());
			} catch (Exception e) {
				log.error("====修改地址id到供应商商品表异常===={}",e);
			}
		} else if (request.getNewAddress() == 1) {
			if (StringUtils.isEmpty(request.getId())) {
				throw new ApiException("地址不存在");
			}
			addressId = String.valueOf(request.getId());
			//获取供应商商品id
			Product pro = productMapper.selectByPrimaryKey(request.getProductId());
			//修改地址id到供应商商品表
			try {
				Map<String,String> map1 = new HashMap<>();
				map1.put("bankerProductId",pro.getBankerProductId().toString());
				map1.put("addressId",request.getId().toString());
				HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/returnGoods/updateBankerProductAddressId", map1, supplyApiConfig.getHeadsMap());
			} catch (Exception e) {
				log.error("====修改地址id到供应商商品表异常===={}",e);
			}

		}

		//订单从失败状态修改成售后单时，防止缓存的原状态不存在
		String orderInfoStatus = redisService.get("return:good:orderInfoStatus" + returnGoods.getOrdersInfoId());
		if (StringUtils.isEmpty(orderInfoStatus)) {
			throw new ApiException("订单原状态不存在，请重新申请发起售后！");
		}
		if ((2 == request.getStatus() || 7 == request.getStatus()) && !StringUtils.isEmpty(request.getReturnExpressCompany()) && !StringUtils.isEmpty(request.getReturnExpressNo())) {
			request.setStatus(8);
			request.setServiceStatus(2);
			request.setServiceApplyName(admin.getName());
			request.setServiceApplyId(admin.getId());
			request.setServiceApplyTime(new Date());
			request.setReturnExpressTime(new Date());
		}
		//收货人信息只能支持一次操作，防止手机号变动后，查不到寄回单号物流信息
		if ((!StringUtils.isEmpty(returnGoods.getReceivingAddress()) && !request.getReceivingAddress().equals(returnGoods.getReceivingAddress())) ||
				(!StringUtils.isEmpty(returnGoods.getReceivingPerson()) && !request.getReceivingPerson().equals(returnGoods.getReceivingPerson())) ||
				(!StringUtils.isEmpty(returnGoods.getReceivingPhone()) && !request.getReceivingPhone().equals(returnGoods.getReceivingPhone()))) {
			request.setReceivingAddress(null);
			request.setReceivingPerson(null);
			request.setReceivingPhone(null);
		}
		//修改地址id到该退货订单中
		returnGoodsDao.updateReturnGoodsAddressId(request.getReturnGoodsId(),//退货表id
				Integer.valueOf(addressId),
				request.getReasonType(),//退货类型
				request.getRefundFare(),//是否退运费
				request.getRefundFareOther(),//退运费备注
				request.getServiceDesc(),//客服描述说明
				request.getReturnOrderNo(),//回传订单号
				request.getReturnExpressCompany(),//物流公司
				request.getReturnExpressNo(),//物流单号
				request.getStatus(),//退货状态
				request.getServiceBeizhu(),
				request.getReturnExpressTime(),
				request.getReceivingPhone(),
				request.getReceivingPerson(),
				request.getReceivingAddress(),
				request.getRelatedPhone(),request.getServiceStatus(),request.getServiceApplyTime(),request.getServiceApplyName(),request.getServiceApplyId());
		try {
			YxReturnGoods yxReturnGoods = new YxReturnGoods();
			yxReturnGoods.setServiceNo(returnGoods.getServiceNo());
			yxReturnGoods.setId(null);
			yxReturnGoods.setStatus(request.getStatus());
			yxReturnGoods.setRefundFare(request.getRefundFare());
			yxReturnGoods.setReturnExpressTime(request.getReturnExpressTime());
			yxReturnGoods.setReturnExpressNo(request.getReturnExpressNo());
			yxReturnGoods.setReturnExpressCompany(request.getReturnExpressCompany());
			yxReturnGoods.setServiceStatus(request.getServiceStatus());
			yxReturnGoods.setServiceApplyTime(request.getServiceApplyTime());
			yxReturnGoods.setReceivingPhone(request.getReceivingPhone());
			yxReturnGoods.setReceivingPerson(request.getReceivingPerson());
			yxReturnGoods.setReceivingAddress(request.getReceivingAddress());
			yxReturnGoods.setServiceDesc(request.getServiceDesc());
			yxReturnGoods.setRefundFareOther(request.getRefundFareOther());
			yxReturnGoods.setServiceBeizhu(request.getServiceBeizhu());
			yxReturnGoods.setReasonType(request.getReasonType());
			yxReturnGoods.setAddressId(Integer.valueOf(addressId));
			yxReturnGoods.setShopId(supplyApiConfig.getShopId());
			yxReturnGoods.setRelatedPhone(request.getRelatedPhone());
			String json = JSON.toJSONString(yxReturnGoods);
			log.debug("============修改返商信息=========参数=={}",json);
			HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/returnGoods/updateReturnGoods", json, supplyApiConfig.getHeadsMap());
		} catch (BeansException e) {
			log.error("====修改售后信息异常===={}",e);
		}

		//记录操作
		GoodReturnInfoVO goodReturnInfoVO = new GoodReturnInfoVO();
		goodReturnInfoVO.setServiceNo(returnGoods.getServiceNo());
		goodReturnInfoVO.setRefundFare(returnGoods.getRefundFare());
		goodReturnInfoVO.setAddressId(request.getId());
		goodReturnInfoVO.setReasonType(request.getReasonType());
		goodReturnInfoVO.setServiceDesc(request.getServiceDesc());
		goodReturnInfoVO.setReturnExpressCompany(request.getReturnExpressCompany());
		goodReturnInfoVO.setReturnExpressNo(request.getReturnExpressNo());
		goodReturnInfoVO.setNewAddress(request.getNewAddress());
		goodReturnInfoVO.setReceivingPhone(request.getReceivingPhone());
		goodReturnInfoVO.setReceivingPerson(request.getReceivingPerson());
		goodReturnInfoVO.setReceivingAddress(request.getReceivingAddress());
		goodReturnInfoVO.setRelatedPhone(request.getRelatedPhone());
		adminModuleLogService.recordReturnBankerInfo(goodReturnInfoVO,ModuleEnum.RETURN_BANKER_INFO.getType(),2,returnGoods.getServiceNo());
	}

	/**
	 * 退货数据,手动修改退货状态为已寄回待处理
	 * @param id
	 * @return
	 */
	@Override
	public Integer updateStatus(Integer id) {
		//先查询退货信息
		ReturnGoods returnGoods = returnGoodsMapper.selectByPrimaryKey(id);
		if (null == returnGoods){
			throw new ApiException("退货信息不存在");
		}
		if(!returnGoods.getStatus().equals(8)){
			throw new ApiException("退货状态为寄回中才能修改哦");
		}
		returnGoods.setStatus(3);
		returnGoods.setGetExpressTime(new Date());
		Integer count = returnGoodsMapper.updateByPrimaryKeySelective(returnGoods);
		try {
			YxReturnGoods yxReturnGoods = new YxReturnGoods();
			yxReturnGoods.setServiceNo(returnGoods.getServiceNo());
			BeanUtils.copyProperties(returnGoods,yxReturnGoods);
			yxReturnGoods.setId(null);
			yxReturnGoods.setShopId(supplyApiConfig.getShopId());
			String json = JSON.toJSONString(yxReturnGoods);
			HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/returnGoods/updateReturnGoods", json, supplyApiConfig.getHeadsMap());
		} catch (BeansException e) {
			log.error("====修改售后信息异常===={}",e);
		}
		return count;
	}

	@Override
	public CommonResult batchAuditSuccess(List<Integer> ids) {
		List<String> failMsg = new ArrayList<>();
		for (Integer id : ids) {
			try {
				auditSuccess(id);
			} catch (Exception e) {
				ReturnOrdersDetail ordersInfo = returnGoodsDao.getOrdersInfo(id);
				if(ordersInfo == null){
					failMsg.add("当前售后单的子订单不存在！");
				}else {
					failMsg.add(String.format("%s操作失败！,%s",ordersInfo.getChildOrderNo(),e.getMessage()));
				}
			}
		}
		return CommonResult.success(failMsg);
	}

	@Override
	public Integer auditFail(Integer id, String serviceRemarks, String rejectType) {
		ReturnGoods returnGoods = returnGoodsMapper.selectByPrimaryKey(id);
		if (returnGoods.getAfterType().equals(1) && returnGoods.getBankerStatus().equals(1)){
			throw new ApiException("该售后类型为退款,供应商审核后,客服才能审核");
		}
		if (returnGoods.getStatus() == 1){
			//把拒绝类型放在redis中
			redisService.set("return:good:audit:reject:type:" + returnGoods.getOrdersInfoId(), rejectType);
			redisService.expire("return:good:audit:reject:type:" + returnGoods.getOrdersInfoId(), 3600 * 24 * 20);
			redisService.expire("return:good:audit:reject:type:" + id, 3600 * 24 * 20);

			//客服审核不通过次数
			redisService.increment("return:good:audit:fail:" + id, 1);
			redisService.expire("return:good:audit:fail:" + id, 3600 * 24 * 7);


			//恢复原有的状态
			String orderInfoStatus = redisService.get("return:good:orderInfoStatus" + returnGoods.getOrdersInfoId());
			OrdersInfo ordersInfo = ordersInfoMapper.selectByPrimaryKey(returnGoods.getOrdersInfoId());
			if(StringUtils.isEmpty(orderInfoStatus)){
				FeiShuUtil.sendMsg(String.format("售后订单%s 撤销失败，订单原状态不存在！",returnGoods.getServiceNo()));
			}
			if (!org.springframework.util.StringUtils.isEmpty(orderInfoStatus)){
				ordersInfo.setOrderinfoStatus(orderInfoStatus);
				int i = ordersInfoMapper.updateByPrimaryKeySelective(ordersInfo);
				if (i>0){
					UpdateOrderStatusRequest updateOrderStatusRequest = new UpdateOrderStatusRequest();
					updateOrderStatusRequest.setChildOrderNo(ordersInfo.getChildOrderNo());
					updateOrderStatusRequest.setShopId(supplyApiConfig.getShopId());
					updateOrderStatusRequest.setOrderStatus(Integer.valueOf(orderInfoStatus));
					String json = JSON.toJSONString(updateOrderStatusRequest);
					HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/order/updateOrderStatus", json, supplyApiConfig.getHeadsMap());
				}
				//查询该子订单所属的主订单有多少个子订单
				OrdersInfoExample ordersInfoExample = new OrdersInfoExample();
				ordersInfoExample.createCriteria().andOrderIdEqualTo(ordersInfo.getOrderId());
				List<OrdersInfo> ordersInfos = ordersInfoMapper.selectByExample(ordersInfoExample);
				if (ordersInfos.size() > 0 && ordersInfos.size() < 2){
					Orders orders = new Orders();
					orders.setOrderStatus(orderInfoStatus);
					orders.setId(ordersInfo.getOrderId());
					ordersMapper.updateByPrimaryKeySelective(orders);
				}else {
					//TODO 如果有多个子订单的情况下,主订单有没有修改,要不要把主订单恢复
					int index = 0;
					for (OrdersInfo info : ordersInfos) {
						if (info.getOrderinfoStatus().equals("6")) {
							index += 1;
						}
					}
					if (index == ordersInfos.size()){
						Orders orders = new Orders();
						orders.setOrderStatus(orderInfoStatus);
						orders.setId(ordersInfo.getOrderId());
						ordersMapper.updateByPrimaryKeySelective(orders);
					}
				}
			} else {
				FeiShuUtil.sendMsg(String.format("子订单号为: %s 的售后订单审核失败，订单原状态不存在！",ordersInfo.getChildOrderNo()));
			}
			try {
				YxReturnGoods yxReturnGoodsRequest = new YxReturnGoods();
				yxReturnGoodsRequest.setServiceNo(returnGoods.getServiceNo());
				yxReturnGoodsRequest.setChildOrderNo(ordersInfo.getChildOrderNo());
				yxReturnGoodsRequest.setServiceStatus(3);
				yxReturnGoodsRequest.setServiceApplyTime(new Date());
				yxReturnGoodsRequest.setStatus(5);
				yxReturnGoodsRequest.setServiceRemarks(serviceRemarks);
				updateReturnGoods(yxReturnGoodsRequest);
			} catch (Exception e) {
				e.printStackTrace();
			}
			//发送审核失败短信
			try{
				if (returnGoods.getAfterType().equals(2) || returnGoods.getAfterType().equals(3)) {
					Orders orders = ordersDao.getOrdersByOrderInfoId(returnGoods.getOrdersInfoId());
					if (!StringUtils.isEmpty(orders.getTel())) {
						SmsDto dto = new SmsDto();
						dto.setType(10);
						dto.setPhone(orders.getTel());
						String code = String.format(auditFailContent, serviceRemarks);
						dto.setCode(code);
						String shopId = supplyApiConfig.getShopId();
						if ("GUOB004".equals(shopId) || "GUOB005".equals(shopId) || "GUOB006".equals(shopId) || "GUOB007".equals(shopId)) {
							guchuangRabbitTemplate.convertAndSend(QueueConstants.SMS_QUEUE, dto);
						}
//						else if ("JUMD005".equals(shopId) || "JUMD006".equals(shopId) || "JUMD007".equals(shopId)|| "JUMD008".equals(shopId)) {
//							jumaiduoRabbitTemplate.convertAndSend(QueueConstants.SMS_QUEUE, dto);
//						} else if ("YQKJ006".equals(shopId) || "YQKJ007".equals(shopId) || "YQKJ008".equals(shopId) || "YQKJ009".equals(shopId)) {
//							yiquanRabbitTemplate.convertAndSend(QueueConstants.SMS_QUEUE, dto);
//						} else if ("ZXLP005".equals(shopId) || "ZXLP006".equals(shopId) || "ZXLP007".equals(shopId) || "YQKJ008".equals(id) ) {
//							zxlpRabbitTemplate.convertAndSend(QueueConstants.SMS_QUEUE, dto);
//						} else if ("YGYX005".equals(shopId) || "YGYX006".equals(shopId) || "YGYX007".equals(shopId) || "YGYX008".equals(id) ) {
//							ygyxRabbitTemplate.convertAndSend(QueueConstants.SMS_QUEUE, dto);
//						} else if ("YXHD005".equals(shopId) || "YXHD006".equals(shopId) || "YXHD007".equals(shopId) || "YXHD008".equals(id) ) {
//							yxhdRabbitTemplate.convertAndSend(QueueConstants.SMS_QUEUE, dto);
//						}
					} else {
						log.error("发送审核成功短信失败原因为订单的用户手机号码为空!");
					}
				}
			}catch (Exception e) {
				log.error("发送审核失败短信失败：{}",e);
			}
			returnDutyService.updateDutyDel(returnGoods.getOrdersInfoId(),returnGoods.getServiceNo(),ordersInfo.getChildOrderNo());
			return returnGoodsDao.auditFail(id, serviceRemarks, memberService.getAdmin().getId(), memberService.getAdmin().getName());
		}
		throw new ApiException("提示：状态为退货中/审核中的数据，才允许进行审核操作！");
	}

	@Override
	public void synvReturnInfo(ReturnGoodsSyncRequest request) {
		ReturnGoods returnGoods = returnGoodsDao.getReturnGoodsById(request.getId());
		if (null != returnGoods
				&& StringUtils.isEmpty(returnGoods.getReturnExpressNo())
				&& !StringUtils.isEmpty(request.getReturnExpressNo())
				&& ReturnGoodsStatusEnums.FAIL.getStatus().equals(returnGoods.getStatus())) {
			request.setStatus(ReturnGoodsStatusEnums.EXPRESSING.getStatus());
		}
		returnGoodsDao.synvReturnInfo(request);
	}

	@Override
	//@Transactional(rollbackFor = Exception.class)
	public Integer refundGoods(Integer id, String refundDesc) {
		// 1.获取退货信息
		ReturnGoods returnGoods = returnGoodsDao.getReturnGoodsById(id);
		if(returnGoods.getStatus() != 3) {
			throw new ApiException("提示：供应商确认收到货物后，才可以进行退款操作！");
		}

		// 2.获取订单详情信息
		OrdersInfo ordersInfo = ordersInfoMapper.selectByPrimaryKey(returnGoods.getOrdersInfoId());

		// 3.查询订单
		Orders orders = ordersMapper.selectByPrimaryKey(ordersInfo.getOrderId());

		// 验证
		if (orders.getIsPay().byteValue() == (byte) 0) {
			throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.ORDER_NOT_REFUND));
		}
		if (orders.getIsRefund().intValue() == 1) {
			throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.NOT_START_REFUND));
		}

		OrdersRefundExample example = new OrdersRefundExample();
		example.createCriteria()
				.andOrderNoEqualTo(orders.getOrderNo());

		List<OrdersRefund> refundList = refundMapper.selectByExample(example);

		OrdersRefund ordersRefund;
		if (refundList != null && refundList.size() > 0) {
			ordersRefund = refundList.get(0);
			if (ordersRefund.getStatus().intValue() == 1) {
				throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.APPLICATION_FOR_DRAWBACK));
			}
			if (ordersRefund.getStatus().intValue() == 2) {
				throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.NOT_START_REFUND));
			}
		} else {
			String refundNo = OrderUtils.getRefundCode(orders.getId());
			Integer totalFee = orders.getRealTotalMoney().multiply(new BigDecimal(100)).intValue();
			Integer refundFee = ordersInfo.getProductPrice().multiply(new BigDecimal(100)).intValue();
			ordersRefund = new OrdersRefund();
			ordersRefund.setOrderNo(orders.getOrderNo());
			ordersRefund.setTradeNo(orders.getTradeNo());
			ordersRefund.setRefundNo(refundNo);
			ordersRefund.setTotalFee(totalFee);
			ordersRefund.setRefundFee(refundFee);
			ordersRefund.setRefundDesc(refundDesc);
			ordersRefund.setCreateTime(new Date());
			ordersRefund.setStatus(1);
			refundMapper.insertSelective(ordersRefund);
		}

		// 获取该订单下的支付信息
		OrdersPay ordersPay = ordersDao.queryOrdersPayByResOrderNo(orders.getTradeNo());

		/*Integer result = 0;
		if ("aliPay".equals(ordersPay.getTradeType())) {
			try {
				AlipayTradeRefundResponse response = alipayService.refundAliPayOrder(orders.getTradeNo(), ordersRefund.getRefundNo(),
						ordersRefund.getTotalFee(), ordersRefund.getRefundFee(), refundDesc);
				if (!response.getMsg().equals("Success") || !response.getCode().equals("10000")) {
					ordersRefund.setStatus(3);
					ordersRefund.setResText(JSONObject.toJSONString(response));
					refundMapper.updateByPrimaryKeySelective(ordersRefund);
					throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.REFUND_FAILED) +":" + response.getSubMsg());
				} else {
					// 退款表状态更新
					ordersRefund.setStatus(2);
					ordersRefund.setResText(JSONObject.toJSONString(response));
					refundMapper.updateByPrimaryKeySelective(ordersRefund);
					// 订单修改
					Orders order = new Orders();
					order.setOrderStatus("6");
					order.setIsRefund(1);
					order.setRefundNo(ordersRefund.getRefundNo());
					OrdersExample ordersExample = new OrdersExample();
					ordersExample.createCriteria()
							.andOrderNoEqualTo(ordersRefund.getOrderNo());
					// 订单修改
					ordersMapper.updateByExampleSelective(order, ordersExample);
					// 订单详情修改
					ordersDao.updateStatusByOrderId("6", order.getId());
					// 同步原路返回页退款时间

					// 查询订单明细 (一条订单存在多条订单明细)
					List<Integer> orderInfoIdList = ordersDao.getOrderInfoId(orders.getId());
					if (!CollectionUtils.isEmpty(orderInfoIdList)) {
						for(Integer orderInfoId : orderInfoIdList) {
							returnRegisterDao.modifiedReturnRegister(orderInfoId);
						}
					}

					// 同步退货管理中的退货状态
					result = returnGoodsDao.returnGoodsSuccess(id);
				}
			} catch (ApiException e) {
				throw e;
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			Map<String, String> response = new HashMap<>();
			if(orders.getOrderSource().equals("h5")){
				response = mallClient.h5RefundOrders(ordersPay.getTradeType(), orders.getTradeNo(), ordersRefund.getRefundNo(),
						ordersRefund.getTotalFee(), ordersRefund.getRefundFee(), refundDesc);
			}else{
				response = mallClient.refundOrders(ordersPay.getTradeType(), orders.getTradeNo(), ordersRefund.getRefundNo(),
						ordersRefund.getTotalFee(), ordersRefund.getRefundFee(), refundDesc);
			}
			if (!response.get("return_code").equals("SUCCESS")) {
				ordersRefund.setStatus(3);
				ordersRefund.setResText(JSONObject.toJSONString(response));
				refundMapper.updateByPrimaryKeySelective(ordersRefund);
				throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.REFUND_FAILED) +":"+ response.get("return_msg"));
			}
			if (!response.get("result_code").equals("SUCCESS")) {
				ordersRefund.setStatus(3);
				ordersRefund.setResText(JSONObject.toJSONString(response));
				refundMapper.updateByPrimaryKeySelective(ordersRefund);
				throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.REFUND_FAILED) +":" + response.get("err_code_des"));
			}

			ordersRefund.setStatus(2);
			ordersRefund.setResText(JSONObject.toJSONString(response));
			refundMapper.updateByPrimaryKeySelective(ordersRefund);
			// 订单修改
			Orders order = new Orders();
			order.setOrderStatus("6");
			order.setIsRefund(1);
			order.setRefundNo(ordersRefund.getRefundNo());
			OrdersExample ordersExample = new OrdersExample();
			ordersExample.createCriteria()
					.andOrderNoEqualTo(ordersRefund.getOrderNo());
			ordersMapper.updateByExampleSelective(order, ordersExample);
			ordersDao.updateStatusByOrderId("6", orders.getId());

			// 查询订单明细 (一条订单存在多条订单明细)
			List<Integer> orderInfoIdList = ordersDao.getOrderInfoId(orders.getId());
			if (!CollectionUtils.isEmpty(orderInfoIdList)) {
				for(Integer orderInfoId : orderInfoIdList) {
					log.info("修改原路返回页开始, {}------------>", orders.getId());
					returnRegisterDao.modifiedReturnRegister(orderInfoId);
					log.info("修改原路返回页结束, {} ------------>", orderInfoId);
				}
			}

			// 同步退货管理中的退货状态
			result = returnGoodsDao.returnGoodsSuccess(id);
		}

		return result;*/
		return ((ReturnGoodsServiceImpl) AopContext.currentProxy()).handleRefundV3(orders,ordersRefund,ordersPay,id,refundDesc);
	}
	@Transactional(rollbackFor = Exception.class)
	@Override
	public Integer handleRefundV3(Orders orders,OrdersRefund ordersRefund,OrdersPay ordersPay,Integer id, String refundDesc){
		Integer result = 0;
		if ("aliPay".equals(ordersPay.getTradeType())) {
			try {
				AlipayTradeRefundResponse response = alipayService.refundAliPayOrder(orders.getTradeNo(), ordersRefund.getRefundNo(),
						ordersRefund.getTotalFee(), ordersRefund.getRefundFee(), refundDesc,ordersPay.getChildId());
				if (!response.getMsg().equals("Success") || !response.getCode().equals("10000")) {
					ordersRefund.setStatus(3);
					ordersRefund.setResText(JSONObject.toJSONString(response));
					refundMapper.updateByPrimaryKeySelective(ordersRefund);
					throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.REFUND_FAILED) +":" + response.getSubMsg());
				} else {
					// 退款表状态更新
					ordersRefund.setStatus(2);
					ordersRefund.setResText(JSONObject.toJSONString(response));
					refundMapper.updateByPrimaryKeySelective(ordersRefund);
					// 订单修改
					Orders order = new Orders();
					order.setOrderStatus("6");
					order.setIsRefund(1);
					order.setRefundNo(ordersRefund.getRefundNo());
					OrdersExample ordersExample = new OrdersExample();
					ordersExample.createCriteria()
							.andOrderNoEqualTo(ordersRefund.getOrderNo());
					// 订单修改
					ordersMapper.updateByExampleSelective(order, ordersExample);
					// 订单详情修改
					ordersDao.updateStatusByOrderId("6", order.getId());
					// 同步原路返回页退款时间

					// 查询订单明细 (一条订单存在多条订单明细)
					List<Integer> orderInfoIdList = ordersDao.getOrderInfoId(orders.getId());
					if (!CollectionUtils.isEmpty(orderInfoIdList)) {
						for(Integer orderInfoId : orderInfoIdList) {
							returnRegisterDao.modifiedReturnRegister(orderInfoId);
						}
					}

					// 同步退货管理中的退货状态
					result = returnGoodsDao.returnGoodsSuccess(id);
				}
			} catch (ApiException e) {
				throw e;
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			Map<String, String> response = new HashMap<>();
			if(orders.getOrderSource().equals("h5")){
				response = mallClient.h5RefundOrders(ordersPay.getTradeType(), orders.getTradeNo(), ordersRefund.getRefundNo(),
						ordersRefund.getTotalFee(), ordersRefund.getRefundFee(), refundDesc);
			}else{
				response = mallClient.refundOrders(ordersPay.getTradeType(), orders.getTradeNo(), ordersRefund.getRefundNo(),
						ordersRefund.getTotalFee(), ordersRefund.getRefundFee(), refundDesc);
			}
			if (!"SUCCESS".equals(response.get("return_code")) &&!"PROCESSING".equals(response.get("return_code"))) {
				ordersRefund.setStatus(3);
				ordersRefund.setResText(JSONObject.toJSONString(response));
				refundMapper.updateByPrimaryKeySelective(ordersRefund);
				throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.REFUND_FAILED) +":"+ response.get("return_msg"));
			}
			if (!"SUCCESS".equals(response.get("return_code")) &&!"PROCESSING".equals(response.get("return_code"))) {
				ordersRefund.setStatus(3);
				ordersRefund.setResText(JSONObject.toJSONString(response));
				refundMapper.updateByPrimaryKeySelective(ordersRefund);
				throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.REFUND_FAILED) +":" + response.get("err_code_des"));
			}

			ordersRefund.setStatus(2);
			ordersRefund.setResText(JSONObject.toJSONString(response));
			refundMapper.updateByPrimaryKeySelective(ordersRefund);
			// 订单修改
			Orders order = new Orders();
			order.setOrderStatus("6");
			order.setIsRefund(1);
			order.setRefundNo(ordersRefund.getRefundNo());
			OrdersExample ordersExample = new OrdersExample();
			ordersExample.createCriteria()
					.andOrderNoEqualTo(ordersRefund.getOrderNo());
			ordersMapper.updateByExampleSelective(order, ordersExample);
			ordersDao.updateStatusByOrderId("6", orders.getId());

			// 查询订单明细 (一条订单存在多条订单明细)
			List<Integer> orderInfoIdList = ordersDao.getOrderInfoId(orders.getId());
			if (!CollectionUtils.isEmpty(orderInfoIdList)) {
				for(Integer orderInfoId : orderInfoIdList) {
					log.info("修改原路返回页开始, {}------------>", orders.getId());
					returnRegisterDao.modifiedReturnRegister(orderInfoId);
					log.info("修改原路返回页结束, {} ------------>", orderInfoId);
				}
			}

			// 同步退货管理中的退货状态
			result = returnGoodsDao.returnGoodsSuccess(id);
		}

		return result;
	}
	@Override
	public void syncReturnRegister(String isRpc) {
		// 获取所有需要同步至原路返回页的数据
		List<ReturnGoods> allData = null;
		String adminFalg = isRpc==null ? null: "2";
		if ("mark".equals(isRpc)){
			allData = returnGoodsDao.queryWaitSyncInfoDataByMarkers();
			adminFalg = isRpc;
		}else{
			allData = returnGoodsDao.queryWaitSyncInfoData();
		}
		doSyncReturnRegister(allData,adminFalg);
	}

	@Override
	public void batchSyncReturnRegister(List<Integer> returnGoodsIds) {
		List<Integer> statusList = returnGoodsDao.selectReturnGoodStatus(returnGoodsIds);
		if (!CollectionUtils.isEmpty(statusList)) {
			List<Integer> collect = statusList.stream().filter(item -> item.equals(1)).collect(Collectors.toList());
			if (!CollectionUtils.isEmpty(collect)) {
				throw new ApiException("有售后单数据暂未审核成功,不能同步到原路返回页");
			}
		}
		List<ReturnGoods> allData = returnGoodsDao.selectReturnGoodsDataByIds(returnGoodsIds);
		//先查一遍该订单是否有存在
		List<Integer> ids = new ArrayList<>();
		allData.forEach(item ->{
			Integer id = returnRegisterDao.selectIdByOrderInfoId(item.getOrdersInfoId());
			if (null == id){
				ids.add(item.getOrdersInfoId());
			}
		});
		//过滤掉在原路返回存在的订单0
		allData = allData.stream().filter(item -> ids.contains(item.getOrdersInfoId())).collect(Collectors.toList());
		if (org.apache.commons.collections.CollectionUtils.isNotEmpty(allData)){
			doSyncReturnRegister(allData,null);
		}else{
			throw new ApiException("该数据已同步，请不要重复同步");
		}
	}

	@Override
	public void syncReturnRegisterById(Integer returnGoodsId) {
		List<ReturnGoods> allData = returnGoodsDao.selectReturnGoodsDataByIds(Lists.newArrayList(returnGoodsId));
		//先查一遍该订单是否有存在
		List<Integer> ids = new ArrayList<>();
		allData.forEach(item ->{
			Integer id = returnRegisterDao.selectIdByOrderInfoId(item.getOrdersInfoId());
			if (null == id){
				ids.add(item.getOrdersInfoId());
			}
		});
		//过滤掉在原路返回存在的订单0
		allData = allData.stream().filter(item -> ids.contains(item.getOrdersInfoId())).collect(Collectors.toList());
		if (org.apache.commons.collections.CollectionUtils.isNotEmpty(allData)){
			doSyncReturnRegister(allData,"1");
		}else{
			throw new ApiException("该数据已同步，请不要重复同步");
		}
	}

	@Override
	public CommonResult deleteReturnGoods(Integer id) {
		ReturnGoods returnGoods = returnGoodsDao.selectById(id);
		//单纯移除
		if (returnGoods.getStatus() == 5 ||returnGoods.getStatus() == 6 ||returnGoods.getStatus() == 7 ||returnGoods.getStatus() == 9 ){
			Map<String,String> map = new HashMap<>();
			map.put("serviceNo",returnGoods.getServiceNo());
			String result = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/returnGoods/deleteReturnGoods", map, supplyApiConfig.getHeadsMap());
			if (Integer.parseInt(result) > 0){
				return CommonResult.success(returnGoodsDao.deleteReturnGoods(id));
			}
		}else { //撤回
			String orderInfoStatus = redisService.get("return:good:orderInfoStatus" + returnGoods.getOrdersInfoId());
			Map<String,String> map = new HashMap<>();
			map.put("serviceNo",returnGoods.getServiceNo());
			map.put("orderInfoStatus",orderInfoStatus);
			String result = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/returnGoods/deleteReturnGoods", map, supplyApiConfig.getHeadsMap());
			if (Integer.parseInt(result) > 0){
				OrdersInfo ordersInfo = ordersInfoMapper.selectByPrimaryKey(returnGoods.getOrdersInfoId());
				if (ordersInfo.getOrderinfoStatus().equals("6")){
					ordersInfo.setOrderinfoStatus(orderInfoStatus);
					ordersInfoMapper.updateByPrimaryKeySelective(ordersInfo);
				}
				return CommonResult.success(returnGoodsDao.deleteReturnGoods(id));
			}
		}
		return CommonResult.failed();
	}

	@Override
	public CommonResult removeReturnGoods(Integer id) {
		Admin admin = UserUtil.getAdmin();
		ReturnGoods returnGoods = returnGoodsDao.selectById(id);
		if (returnGoods.getStatus() == 5 ||returnGoods.getStatus() == 6 ||returnGoods.getStatus() == 7 ||returnGoods.getStatus() == 9 ){
			throw new ApiException("售后进行中才能撤销");
		}else { //撤回
			String orderInfoStatus = redisService.get("return:good:orderInfoStatus" + returnGoods.getOrdersInfoId());
			OrdersInfo ordersInfo = ordersInfoMapper.selectByPrimaryKey(returnGoods.getOrdersInfoId());
			log.info("售后单之前子订单Redis的状态是:{},子订单号childOrderNo:{}",orderInfoStatus,ordersInfo.getChildOrderNo());
			if (StringUtils.isEmpty(orderInfoStatus) || OrderStatusEnums.REFUND.getStatus().equals(orderInfoStatus)) {
				FeiShuUtil.sendMsg(String.format("售后订单%s 撤销失败，订单原状态 %s", returnGoods.getServiceNo(), StringUtils.isEmpty(orderInfoStatus) ? "不存在！" : "6"));
				//防止Redis保存的是售后状态，那订单撤销了不能回到原状态了。
				if (!StringUtils.isEmpty(ordersInfo.getExpressNo()) && !StringUtils.isEmpty(ordersInfo.getExpressCompanyNo())) {
					orderInfoStatus = OrderStatusEnums.DELIVERY.getStatus();
				} else {
					orderInfoStatus = OrderStatusEnums.WAIT_DELIVERY.getStatus();
				}
			}
			returnGoods.setRemoveName(admin.getName());
			returnGoods.setRemoveNameId(admin.getId());
			returnGoods.setRemoveTime(new Date());
			List<ReturnGoods> returnGoodsList = returnGoodsDao.getListByOrderInfoId(ordersInfo.getId());
			//不正常的数据，不应该有同一个订单两条正在售后；只需要撤销当前售后订单,无需回到原状态
			if(returnGoodsList.size() > 1){
				returnGoods.setStatus(6);
				returnGoodsMapper.updateByPrimaryKey(returnGoods);
				returnDutyService.updateDutyDel(returnGoods.getOrdersInfoId(),returnGoods.getServiceNo(),ordersInfo.getChildOrderNo());
				//修改供应链售后状态
				Map<String,String> map = new HashMap<>();
				map.put("serviceNo",returnGoods.getServiceNo());
				HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/returnGoods/removeReturnGoods", map, supplyApiConfig.getHeadsMap());
				FeiShuUtil.sendMsg(String.format("撤销操作异常，当前有两条售后中的记录，已撤销当前售后：%s，订单状态不变！", returnGoods.getServiceNo()));
				return CommonResult.success("数据异常，当前有两条售后中的记录，已撤销当前售后~");
			}
			//如果为退款订单，需要查询该订单是否已推送到供应链
			log.info("售后单afterType:{},子订单号childOrderNo:{}",returnGoods.getAfterType(),ordersInfo.getChildOrderNo());
			if (1 == returnGoods.getAfterType()) {
				OrderQueryRequest orderQueryRequest = new OrderQueryRequest();
				orderQueryRequest.setChildOrderNo(Arrays.asList(ordersInfo.getChildOrderNo()));
				String jsonStr = JSONObject.toJSONString(orderQueryRequest);
				String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/order/selectByChildOrderNo", jsonStr, supplyApiConfig.getHeadsMap());
				log.debug("=========供应链不存在的订单===========childOrderNo:{}",resultJson);
				//没有推送到供应链
				if (!org.springframework.util.StringUtils.isEmpty(resultJson) && !"[]".equals(resultJson)) {
					List<String> childOrderNoList = JSONArray.parseArray(resultJson, String.class);
					if (!CollectionUtils.isEmpty(childOrderNoList)){
						if (ordersInfo.getOrderinfoStatus().equals("6")){
							ordersInfo.setOrderinfoStatus(orderInfoStatus);
							ordersInfoMapper.updateByPrimaryKeySelective(ordersInfo);
							// 订单修改
							List<OrdersInfo> ordersInfoList = ordersDao.getAllOrdersInfoByOrderId(ordersInfo.getOrderId());
							if (!CollectionUtils.isEmpty(ordersInfoList) && ordersInfoList.size() == 1) {
								Orders order = new Orders();
								order.setOrderStatus(orderInfoStatus);
								order.setId(ordersInfo.getOrderId());
								ordersMapper.updateByPrimaryKeySelective(order);
							}else {
								if (!CollectionUtils.isEmpty(ordersInfoList)) {
									int index = 0;
									for (OrdersInfo info : ordersInfoList) {
										if (!("4,5,6".contains(info.getOrderinfoStatus()))){
											index += 1;
										}
									}
									if (index == ordersInfoList.size()) {
										Orders order = new Orders();
										order.setOrderStatus(orderInfoStatus);
										order.setId(ordersInfo.getOrderId());
										ordersMapper.updateByPrimaryKeySelective(order);
									}
								}
							}
						}
						returnGoods.setStatus(6);
						try {
							if (checkPayDate(ordersInfo.getOrderId())){
								mallClient.ordersUpload(ordersInfo.getOrderId());
							}
						} catch (Exception e) {
							log.error("===========售后撤销推送订单异常============{}",e);
						}
						returnDutyService.updateDutyDel(returnGoods.getOrdersInfoId(),returnGoods.getServiceNo(),ordersInfo.getChildOrderNo());
//						//清除缓存
//						redisService.delete("return:good:orderInfoStatus" + returnGoods.getOrdersInfoId());
						return CommonResult.success(returnGoodsMapper.updateByPrimaryKey(returnGoods));
					}
				}
			}
			Map<String,String> map = new HashMap<>();
			map.put("serviceNo",returnGoods.getServiceNo());
			map.put("orderInfoStatus",orderInfoStatus);
			log.info("修改供应商售后单和订单状态结果:{}",JSONObject.toJSONString(map));
			String result = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/returnGoods/removeReturnGoods", map, supplyApiConfig.getHeadsMap());
			log.info("修改供应商售后单和订单状态结果:{}",result);
			if (Integer.parseInt(result) > 0){
				if (ordersInfo.getOrderinfoStatus().equals("6")){
					ordersInfo.setOrderinfoStatus(orderInfoStatus);
					int i = ordersInfoMapper.updateByPrimaryKeySelective(ordersInfo);
					if(i > 0){
						Orders order = new Orders();
						order.setOrderStatus(orderInfoStatus);
						order.setId(ordersInfo.getOrderId());
						ordersMapper.updateByPrimaryKeySelective(order);
					}
				}
				returnGoods.setStatus(6);
				returnDutyService.updateDutyDel(returnGoods.getOrdersInfoId(),returnGoods.getServiceNo(),ordersInfo.getChildOrderNo());
				return CommonResult.success(returnGoodsMapper.updateByPrimaryKey(returnGoods));
			}
		}
		return CommonResult.failed();
	}

	@Override
//	@Transactional(rollbackFor = Exception.class)
	public CommonResult creatReturnGoods(ReturnGoodsReq request) {
		Admin admin = memberService.getAdmin();
		OrdersForbid ordersForbid = new OrdersForbid();
		ordersForbid.setOrdersInfoId(request.getOrdersInfoId());
		ordersForbid.setForbidType(1);
		//是否禁止售后
		OrdersForbidResponse lockOrderInfo = ordersForbidMapper.getLockOrderInfo(ordersForbid);
		if(lockOrderInfo != null && lockOrderInfo.getStatus() == 0){
			throw new ApiException("该订单已被禁止售后！请解除后再试！");
		}
		if(StringUtils.isEmpty(admin.getName()) || admin.getId() == null){
			throw new ApiException("无法获取登录用户信息！");
		}
		if(request.getAmount() == null || request.getAmount().compareTo(BigDecimal.ZERO) < 1){
			throw new ApiException("请正确填写退款金额！");
		}
		if(request.getOrderType() == null){
			throw new ApiException("订单类型为必填项！");
		}
		if(request.getDutyReasonType() == null || StringUtils.isEmpty(request.getDutyReasonTypeText())){
			throw new ApiException("原因类型为必填项！");
		}
		if(request.getReasonSecondType() == null || StringUtils.isEmpty(request.getReasonSecondTypeText())){
			throw new ApiException("问题归类为必填项！");
		}
		if (StringUtils.isEmpty(request.getReasonDetail())) {
			throw new ApiException("具体原因为必填项！");
		}
		if(request.getAfterType() == 3){
			if(request.getIsIntercept() == null){
				throw new ApiException("特殊备注为必填项！");
			}
			if(request.getIsGet() == null){
				throw new ApiException("是否收货为必填项！");
			}
		}

		RLock lock = redissonClient.getLock("RETURN_GOODS_LOCK_" + request.getOrdersInfoId());
		boolean b = false;
		try {
			b = lock.tryLock(0, 5, TimeUnit.SECONDS);
		} catch (InterruptedException e) {
			lock.unlock();
			throw new ApiException("系统异常，发起售后失败！");
		}
		if (!b) {
			throw new ApiException("售后申请中,请勿重复申请");
		}

		OrdersInfo info = ordersInfoMapper.selectByPrimaryKey(request.getOrdersInfoId());

		if(null == info) {
			throw new ApiException("未找到订单,或当前订单未支付！");
		}

		if (info.getOrderinfoStatus().equals("0")){
			throw new ApiException("该订单未付款");
		}
		if (info.getOrderinfoStatus().equals("4")) {
			throw new ApiException("该订单已关闭");
		}
		if (info.getOrderinfoStatus().equals("6")) {
			throw new ApiException("该订单正在进行售后");
		}
		if (request.getAfterType().compareTo(1) == 0 && !StringUtils.isEmpty(info.getExpressNo())){
			throw new ApiException("订单已发货,不能申请退款");
		}
		if (request.getAfterType().compareTo(2) == 0 && "1".equals(info.getOrderinfoStatus())){
			throw new ApiException("订单未发货,不能申请退货退款");
		}
		//查询是否存在退货管理中
		if(null != returnGoodsDao.selectByOrderInfoId(request.getOrdersInfoId())) {
			throw new ApiException("该订单已经在退货中");
		}


		//查询用户id
		Orders orders = ordersMapper.selectByPrimaryKey(info.getOrderId());
		try {
			if (checkAbroadOrderCancel(info.getChildOrderNo(), info.getBankerId(), orders.getUserId()) != 1) {
				throw new ApiException("商品已出库，不能申请退款，有疑问请联系客服！");
			}
		} catch (Exception e) {
			log.error("===跨境订单检查能否退货异常==={}", e);
		}
		List<OrderDisparitiesRefund> orderDisparitiesRefunds = orderDisparitiesRefundMapper.querySuccessByOrderNo(orders.getOrderNo());
		BigDecimal refundMoney= BigDecimal.ZERO;
		if (!CollectionUtils.isEmpty(orderDisparitiesRefunds)) {
			refundMoney = orderDisparitiesRefunds.stream().map(item -> ObjectUtils.isEmpty(item.getAmount()) ? new BigDecimal(0) : item.getAmount()).reduce(BigDecimal.ZERO, BigDecimal::add);
		}

		OrdersPay ordersPay = ordersPayMapper.findOrdersPayByOrderNo(orders.getOrderNo());
		BigDecimal amount = ordersPay.getAmount().subtract(refundMoney);
		try {
			if(null != ordersPay && amount.compareTo(request.getAmount())<0){
				throw new ApiException("提交售后金额不能大于实付金额！");
			}
		}catch (Exception e) {
			log.error("检查售后订单金额异常");
			throw new ApiException("提交售后金额不能大于实付金额！");
		}

		List<String> childOrderNo = new ArrayList<>();
		childOrderNo.add(info.getChildOrderNo());
		List<OrderQueryResponse> orderQueryResponses = querySupplyChainOrderInfo(childOrderNo);
		if (!CollectionUtils.isEmpty(orderQueryResponses)) {
			OrderQueryResponse orderQueryResponse = orderQueryResponses.get(0);
			if (request.getAfterType() == 1) {
				if (null != orderQueryResponse.getOrderInfoStatus() && !orderQueryResponse.getOrderInfoStatus().equals(1)) {
					throw new ApiException("商品正在打包中，不能申请退款");
				}
			}
		}

		//是否已存在订单原状态
		String orderInfoStatus = redisService.get("return:good:orderInfoStatus" + request.getOrdersInfoId());
		if (StringUtils.isEmpty(orderInfoStatus) || OrderStatusEnums.REFUND.getStatus().equals(orderInfoStatus) || OrderStatusEnums.REFUND.getStatus().equals(info.getOrderinfoStatus())) {
			if (OrderStatusEnums.REFUND.getStatus().equals(info.getOrderinfoStatus())) {
				if (!StringUtils.isEmpty(info.getExpressNo()) && !StringUtils.isEmpty(info.getExpressCompanyNo())) {
					orderInfoStatus = OrderStatusEnums.DELIVERY.getStatus();
				} else {
					orderInfoStatus = OrderStatusEnums.WAIT_DELIVERY.getStatus();
				}
			} else {
				orderInfoStatus = info.getOrderinfoStatus();
			}
		} else {
			orderInfoStatus = info.getOrderinfoStatus();
		}
		redisService.set("return:good:orderInfoStatus" + request.getOrdersInfoId(), orderInfoStatus);
		redisService.expire("return:good:orderInfoStatus" + request.getOrdersInfoId(), 3600 * 24 * 180);

		//修改订单状态
		Integer i = updateOrderStatus(info);

		if (i < 1){
			throw new ApiException("系统异常,请稍后再试");
		}
		Product product = productMapper.selectByPrimaryKey(info.getProductId());
		//查询地址
		String addressId = "";
		try {
			if (null!= product){
				Map<String,String> map = new HashMap<>();
				map.put("productId",String.valueOf(product.getSupplyProductId()));
				addressId = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/product/getAddressId", map, supplyApiConfig.getHeadsMap());
			}
		} catch (Exception e) {
			log.error("==={}", e);
		}
		//插入数据
		ReturnGoods returnGoods = new ReturnGoods();
		returnGoods.setOrdersStatus(info.getOrderinfoStatus());
		returnGoods.setServiceStatus(1);//客服审核--待审核
		returnGoods.setStatus(1);//退货状态--待审核
		returnGoods.setServiceNo(OrderUtils.getRefundCode(orders.getUserId()));//服务单号
		returnGoods.setOrdersInfoId(request.getOrdersInfoId());//订单详情id
		returnGoods.setAmount(request.getAmount());//退款金额
		returnGoods.setProductId(info.getProductId());//商品id
		returnGoods.setSpec(info.getProductSkuSpec());//商品规格
		returnGoods.setNumber(info.getProductSum());//商品数量
		returnGoods.setUserId(orders.getUserId());//用户id
		returnGoods.setAddressId(org.apache.commons.lang3.StringUtils.isNotBlank(addressId) ? Integer.valueOf(addressId) : null);//返商地址id
		//退款-未收到货(0)；退货退款-已收到货(1)；仅退款-需要页面手动选择(1或0)
		returnGoods.setIsGet(request.getAfterType() == 1 ? 0 : request.getAfterType() == 2 ? 1 : request.getIsGet());
		returnGoods.setReturnReason(request.getReasonSecondTypeText());//退货类型
		returnGoods.setUserRemarks(request.getReasonDetail());//用户退货描述
		returnGoods.setUserRemarksImg(request.getUserRemarksImg());//用户退货凭证
		returnGoods.setBankerStatus(1);//商家审核--待审核
		returnGoods.setCreateTime(new Date());//客服登记时间
		returnGoods.setServiceId(admin.getId());//客服id
		returnGoods.setServiceName(admin.getName());//客服姓名
		returnGoods.setAfterType(request.getAfterType());
		returnGoods.setServiceCheckIn(1);
		returnGoods.setReasonType(request.getDutyReasonTypeText());
		returnGoods.setIsIntercept(request.getAfterType() == 3 ? request.getIsIntercept() : 0);
		returnGoods.setAfterSalesPassUser(admin.getId());
		returnGoods.setAfterSalesPassTime(new Date());
		//登记售后责任表
		ReturnDuty returnDuty = new ReturnDuty();
		try {
			returnDuty.setServiceNo(returnGoods.getServiceNo());
			returnDuty.setOrderType(request.getOrderType());
			returnDuty.setReasonType(request.getDutyReasonType());
			returnDuty.setReasonSecondType(request.getReasonSecondType());
			returnDuty.setReasonDetail(request.getReasonDetail());
			//只有售后责任项全部填写才算已登记，即：1
			returnDuty.setAfterSaleStatus(0);
			returnDuty.setOrderNo(orders.getOrderNo());
			returnDuty.setOrderInfoId(returnGoods.getOrdersInfoId());
			returnDuty.setChildOrderNo(info.getChildOrderNo());
			returnDuty.setRecvName(orders.getUserName());
			returnDuty.setRecvPhone(orders.getUserPhone());
			returnDuty.setAfterType(returnGoods.getAfterType());
			returnDuty.setReturnDutyFee(returnGoods.getAmount());
			log.info("============saveReturnDuty===========returnDuty:{}", JSONObject.toJSONString(returnDuty));
			returnDutyMapper.insertSelective(returnDuty);
			//记录操作
			adminModuleLogService.recordReturnDuty(returnDuty, ModuleEnum.RETURN_DUTY.getType(),1,returnGoods.getServiceNo(),info.getChildOrderNo());
		} catch (Exception e) {
			e.printStackTrace();
		}
		//仅【退款】售后单。验证订单是否存在供应链
		if (1 == request.getAfterType()) {
			OrderQueryRequest orderQueryRequest = new OrderQueryRequest();
			orderQueryRequest.setChildOrderNo(childOrderNo);
			String jsonStr = JSONObject.toJSONString(orderQueryRequest);
			String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/order/selectByChildOrderNo", jsonStr, supplyApiConfig.getHeadsMap());
			log.debug("=========当前销售单子订单号：{}；不在供应链的子订单号有：{}===========",childOrderNo,resultJson);
			//售后类型为退款
			if (!org.springframework.util.StringUtils.isEmpty(resultJson)) {
				List<String> childOrderNoList = JSONArray.parseArray(resultJson, String.class);
				//在供应链不存在，则默认供应商同意售后
				if (!CollectionUtils.isEmpty(childOrderNoList)){
					returnGoods.setBankerStatus(2);
					returnGoods.setBankerApplyTime(new Date());
					returnGoods.setStatus(4);
					JSON.toJSONString(returnGoods);
					returnGoodsMapper.insertSelective(returnGoods);
					if (null != lock) {
						lock.unlock();
					}

					return CommonResult.success(returnGoods);
				}
			}
		}
		//退货退款
		if(2 == request.getAfterType()){
			//退货状态--等待寄回
			returnGoods.setStatus(2);
		}

		Integer count = returnGoodsDao.creat(returnGoods);
		try {
			YxReturnGoods yxReturnGoodsRequest = new YxReturnGoods();
			BeanUtils.copyProperties(returnGoods,yxReturnGoodsRequest);
			yxReturnGoodsRequest.setShopId(supplyApiConfig.getShopId());
			yxReturnGoodsRequest.setChildOrderNo(info.getChildOrderNo());
			yxReturnGoodsRequest.setProductId(product.getSupplyProductId());//存供应链的商品id
			yxReturnGoodsRequest.setProductNum(info.getProductSum());
			//退货订单上传供应链
			log.debug("====上传供应链=====参数{}",yxReturnGoodsRequest);
			String json = JSON.toJSONString(yxReturnGoodsRequest);
			String s = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/returnGoods/returnGoodsUpload", json, supplyApiConfig.getHeadsMap());
			log.debug("====上传供应链=====返回{}",s);
		} catch (Exception e) {
			log.error("====客服登记售后上传供应链失败====={}",e);
		}

		try {
			String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/returnDuty/saveOrUpdateReturnDuty",
					JSONObject.toJSONString(returnDuty), supplyApiConfig.getHeadsMap());
		} catch (Exception e) {
			log.error("调用供应链接口{},出错：","/returnDuty/saveOrUpdateReturnDuty",e.getMessage());
		}

		if (null != lock) {
			lock.unlock();
		}

		//获取操作用户id
		Integer adminId = UserUtil.getAdminId();
		//记录操作小记
		OrderNote orderNote = new OrderNote();
		orderNote.setOrderInfoId(request.getOrdersInfoId());
		orderNote.setContent("同步到退货管理");
		orderNote.setAdminId(adminId);
		orderNoteService.insertOrderNote(orderNote);
		if (count > 0){
			return CommonResult.success("同步到退货管理成功");
		}
		return CommonResult.failed("同步到退货管理失败");

	}

	/**
	 * 检查跨境订单是否能退款
	 * @param childOrderNo
	 * @param bankerId
	 * @param userId
	 * @return 1=能 0=不能
	 */
	private Integer checkAbroadOrderCancel(String childOrderNo, Integer bankerId, Integer userId) {
		YxReturnGoods yxReturnGoods = new YxReturnGoods();
		yxReturnGoods.setChildOrderNo(childOrderNo);
		yxReturnGoods.setBankerId(bankerId);
		yxReturnGoods.setUserId(userId);
		String json = com.gexin.fastjson.JSON.toJSONString(yxReturnGoods);
		String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/returnGoods/checkAbroadOrderCancel", json, supplyApiConfig.getHeadsMap());
		log.info("===checkAbroadOrderCancel==={},{}", childOrderNo, resultJson);
		if (org.springframework.util.StringUtils.isEmpty(resultJson)) {
			log.warn("===供应链检查跨境订单是否能发货返回空了===");
			return 0;
		}
		CommonResult result = JSONObject.parseObject(resultJson, CommonResult.class);
		if (null != result && result.getCode()==200) {
			return 1;
		}
		return 0;
	}

	/**
	 * 修改订单状态为售后订单
	 * @param ordersInfo
	 */
	private Integer updateOrderStatus(OrdersInfo ordersInfo) {
		//修改订单状态
		ordersInfo.setOrderinfoStatus("6");
		Integer i = ordersInfoMapper.updateByPrimaryKeySelective(ordersInfo);
		if (i > 0){
			OrdersInfoExample ordersInfoExample = new OrdersInfoExample();
			ordersInfoExample.createCriteria().andOrderIdEqualTo(ordersInfo.getOrderId());
			List<OrdersInfo> ordersInfos = ordersInfoMapper.selectByExample(ordersInfoExample);
			if (ordersInfos.size() < 2){
				//修改主订单状态
				ordersMapper.updateOrderStatus(ordersInfo.getOrderId(),6);
			}else {
				//判断其他子订单是否为6.售后订单,是就把主订单状态也修改为6.售后订单
				AtomicReference<Boolean> flag = new AtomicReference<>(true);
				ordersInfos.stream().filter(item ->item.getId().equals(ordersInfo.getId())).forEach(item ->{
					if (!item.getOrderinfoStatus().equals("6")) {
						flag.set(false);
					}
				});
				if (flag.get()){
					ordersMapper.updateOrderStatus(ordersInfo.getOrderId(),6);
				}
			}
		}
		return i;
	}

	/**
	 *
	 * @param request
	 * @param ordersInfo
	 * @param addressId
	 * @param userId
	 */
	public Integer createData(ReturnGoodsReq request, OrdersInfo ordersInfo, Integer addressId, Integer userId) {
		ReturnGoods returnGoods = new ReturnGoods();
		returnGoods.setServiceStatus(1);//客服审核--待审核
		returnGoods.setStatus(1);//退货状态--待审核
		returnGoods.setServiceNo(OrderUtils.getRefundCode(userId));//服务单号
		returnGoods.setOrdersInfoId(request.getOrdersInfoId());//订单详情id
		returnGoods.setAmount(request.getAmount());//退款金额
		returnGoods.setProductId(ordersInfo.getProductId());//商品id
		returnGoods.setSpec(ordersInfo.getProductSkuSpec());//商品规格
		returnGoods.setNumber(ordersInfo.getProductSum());//商品数量
		returnGoods.setUserId(userId);//用户id
		returnGoods.setAddressId(null == addressId ? null : addressId);//反商地址id
		returnGoods.setIsGet(request.getIsGet());//是否收到货
		returnGoods.setReturnReason("其它");//退货类型
		returnGoods.setUserRemarks(request.getUserRemarks());//用户退货描述
		returnGoods.setUserRemarksImg(request.getUserRemarksImg());//用户退货凭证
		returnGoods.setBankerStatus(1);//商家审核--待审核
		returnGoods.setServiceApplyTime(new Date());//客服审核时间
		returnGoods.setServiceId(memberService.getAdmin().getId());//客服id
		returnGoods.setServiceName(memberService.getAdmin().getName());//客服姓名
		returnGoods.setAfterType(request.getAfterType());
		returnGoods.setServiceCheckIn(1);
		Integer creat = returnGoodsDao.creat(returnGoods);
		return creat;
	}


	public void doSyncReturnRegister(List<ReturnGoods> allData,String adminFalg) {
		List<Integer> repeatDataFilterList = doRepeatBackDataFilter(allData);
		if (!CollectionUtils.isEmpty(repeatDataFilterList)) {
			for (ReturnGoods data : allData) {
				if (!repeatDataFilterList.contains(data.getOrdersInfoId())) {
					continue;
				}
				// 1.获取退货管理信息
				ReturnGoods returnGoods = returnGoodsDao.getReturnGoodsByOid(data.getOrdersInfoId());
				// 2.获取订单详情信息
				OrdersInfo ordersInfo = ordersInfoMapper.selectByPrimaryKey(data.getOrdersInfoId());
				// 3.获取订单信息
				Orders orders = ordersMapper.selectByPrimaryKey(ordersInfo.getOrderId());

				//来自定时任务，支付宝支付的售后单自动同步。其他的手动处理
				if ("2".equals(adminFalg) && !"alipay".equals(orders.getPaySource())) {
					continue;
				}

				// 同步数据至原路返回页
				ReturnRegister register = new ReturnRegister();
				register.setOrderInfoId(data.getOrdersInfoId());
				//原因类型
				if (null == returnGoods) {
					register.setReasonType(null);
				} else {
					register.setReasonType(StringUtils.isEmpty(returnGoods.getReasonType()) ? null :  ReasonTypeEnums.getCodeByMessage(returnGoods.getReasonType()));
				}
				//具体原因
				register.setSpecificReason(null == returnGoods ? "" : returnGoods.getUserRemarks());
				//原单号
				register.setOldTradeNo(ordersInfo.getExpressNo());
				//寄回单号
				register.setReturnTradeNo(null == returnGoods ? "" : returnGoods.getReturnExpressNo());
				//图片/视频
				register.setUrl(null == returnGoods ? "" : returnGoods.getUserRemarksImg());
				register.setOrderNo(orders.getOrderNo());
				register.setCreateTime(new Date());
				register.setIsPay(Integer.valueOf(orders.getIsPay()));
				register.setPaySource(orders.getPaySource());
				register.setOrderStatus(Integer.parseInt(orders.getOrderStatus()));
				register.setOrderinfoStatus(Integer.valueOf(ordersInfo.getOrderinfoStatus()));
				register.setUserName(orders.getUserName());
				register.setUserPhone(orders.getUserPhone());
				register.setWarehouseName(ordersInfo.getWarehouseName());
				register.setProductName(ordersInfo.getProductName());
				register.setRealTotalMoney(orders.getRealTotalMoney());
				if ("2".equals(adminFalg)|| "mark".equals(adminFalg)) {
					register.setOperationName("");
				} else {
					register.setOperationName(memberService.getAdmin().getName());
				}
				register.setOperationTime(new Date());
				register.setStatus(0);
				if (null != returnGoods) {
					//退货凭证
					register.setFile(returnGoods.getUserRemarksImg());
					//物流单号
					register.setReturnTradeNo(returnGoods.getReturnExpressNo());
					//具体原因
					register.setSpecificReason(returnGoods.getUserRemarks());

					//退货凭证
					if (!StringUtils.isEmpty(returnGoods.getUserRemarksImg())){
						//判断是否为视频
						String[] suffixs = returnGoods.getUserRemarksImg().split("\\.");
						if (null != suffixs && suffixs.length > 1) {
							String suffix = suffixs[suffixs.length - 1];
							String s = "avi、mov、rmvb、rm、flv、mp4、3gp";
							boolean contains = s.contains(suffix.toLowerCase());
							if (contains) {
								register.setFileType("video");
							}else {
								register.setFileType("img");
							}
						}
					}
				}
				// 同步数据至原路返回页
				returnRegisterDao.insertReturnRegister(register);
			}
		}
	}

	/**
	 * 根据供应商id获取供应商退货地址
	 * @param bankerId
	 * @return
	 */
	@Override
	public List<BankerAddressResponse> getReturnAddressByBankerId(Integer bankerId) {
		List<BankerAddressResponse> addresses = bankerDao.selectReturnAddressByBankerId(bankerId);
		addresses.stream().forEach(item -> {
			String pcaAddress = item.getProvince() + item.getCity() + (null == item.getArea() ? "": item.getArea()) + item.getAddress();
			item.setPCAaddress(pcaAddress);
		});
		return addresses;
	}

	@Override
	public List<BankerStoreAddressResponse> newGetReturnAddressByBankerId(Integer bankerId) {
		Map map = new HashMap<>();
		map.put("bankerId", String.valueOf(bankerId));
		String resultJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/returnGoods/getReturnGoodAddress", map, supplyApiConfig.getHeadsMap());
		CommonResult commonResult = JSONObject.parseObject(resultJson, CommonResult.class);
		List<BankerStoreAddressResponse> result = JSONArray.parseArray(commonResult.getData().toString(), BankerStoreAddressResponse.class);
		return result;
	}

	@Override
	public List<BankerStoreAddressResponse> newGetReturnAddressByBankerId(String bankerIds) {
		Map map = new HashMap<>();
		map.put("bankerIds", bankerIds);
		String resultJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/returnGoods/getReturnGoodAddressList", map, supplyApiConfig.getHeadsMap());
		CommonResult commonResult = JSONObject.parseObject(resultJson, CommonResult.class);
		List<BankerStoreAddressResponse> result = null;
		if (commonResult!=null && commonResult.getData() != null){
			result = JSONArray.parseArray(commonResult.getData().toString(), BankerStoreAddressResponse.class);
		}
		return result;
	}

	@Override
	public List<BankerAddressResponse> getReturnAddressByAddressId(Integer addressId) {
		List<BankerAddressResponse> addresses = bankerDao.selectReturnAddressByAddressId(addressId);
		addresses.stream().forEach(item -> {
			String pcaAddress = item.getProvince() + item.getCity() + (null == item.getArea() ? "": item.getArea()) + item.getAddress();
			item.setPCAaddress(pcaAddress);
		});
		return addresses;
	}

	public List<Integer> doRepeatBackDataFilter(List<ReturnGoods> list) {
		List<Integer> paramList = list.stream().map(s -> s.getOrdersInfoId()).collect(Collectors.toList());
		List<ReturnRegister> repeatList = returnRegisterDao.selectByOrderInfoId(paramList);
		List<Integer> repeatIds = repeatList.stream().map(s -> s.getOrderInfoId()).collect(Collectors.toList());
		paramList.removeAll(repeatIds);
		return paramList;
	}

	/**
	 * 更新供应链售后信息
	 */
	public String updateReturnGoods(YxReturnGoods request){
		request.setShopId(supplyApiConfig.getShopId());
		String json = JSON.toJSONString(request);
		log.debug("==============更新供应链售后信息=============/returnGoods/updateReturnGoods=请求:{}",json);
		String s = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/returnGoods/updateReturnGoods", json, supplyApiConfig.getHeadsMap());
		log.debug("==============更新供应链售后信息=============/returnGoods/updateReturnGoods=返回:{}",s);
		return s;
	}

	@Override
	public CommonResult getProvince(Integer id) {
		String resultJson;
		if (id == null) {
			resultJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/banker/getProvince", null, supplyApiConfig.getHeadsMap());
		} else {
			Map map = new HashMap();
			map.put("id",String.valueOf(id));
			resultJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/banker/getProvince", map, supplyApiConfig.getHeadsMap());
		}
		CommonResult commonResult = JSONObject.parseObject(resultJson, CommonResult.class);
		return commonResult;
	}

	@Override
	public CommonResult getCity(Integer id) {
		String resultJson;
		if (id == null) {
			resultJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/banker/getCity", null, supplyApiConfig.getHeadsMap());
		} else {
			Map map = new HashMap();
			map.put("id",String.valueOf(id));
			resultJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/banker/getCity", map, supplyApiConfig.getHeadsMap());
		}

		CommonResult commonResult = JSONObject.parseObject(resultJson, CommonResult.class);

		return commonResult;
	}

	@Override
	public CommonResult getArea(Integer id) {
		Map map = new HashMap();
		map.put("id",String.valueOf(id));
		String resultJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/banker/getArea", map, supplyApiConfig.getHeadsMap());

		CommonResult commonResult = JSONObject.parseObject(resultJson, CommonResult.class);

		return commonResult;
	}

	/**
	 * 查询订单信息
	 * 主要查询物流信息（物流公司编码、快递单号、发货时间、是否导出、导出时间）
	 */
	@Override
	public List<OrderQueryResponse> querySupplyChainOrderInfo(List<String> childOrderNo) {
		OrderQueryRequest orderQueryRequest = new OrderQueryRequest();
		orderQueryRequest.setChildOrderNo(childOrderNo);
		String json = com.gexin.fastjson.JSON.toJSONString(orderQueryRequest);
		String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/order/query", json, supplyApiConfig.getHeadsMap());
		if (org.springframework.util.StringUtils.isEmpty(resultJson)) {
			return new ArrayList<>();
		}
		JSONObject parse = JSON.parseObject(resultJson);
		List<OrderQueryResponse> orderQueryResponses = JSONObject.parseArray(parse.getString("data"), OrderQueryResponse.class);
		return orderQueryResponses;
	}

	/**
	 * 撤销售后且供应链不存在的订单
	 * 判断支付时间是否需要把订单推送到供应链
	 * @return
	 */
	private boolean checkPayDate(Integer orderId) throws ParseException {
		Orders orders = ordersMapper.selectByPrimaryKey(orderId);
		Date payTime = orders.getPayTime();

		//对比前一天14点,小于则需要推送
		LocalDate ld = LocalDate.now(ZoneId.systemDefault());
		ld = ld.plusDays(-1);
		LocalDateTime localDateTime = ld.atTime(14, 0);
		long time = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()).getTime();

		if (time > payTime.getTime()){
			//支付时间小于前一天14点
			return true;
		}
		//对比当前时间,当前时间大于当前14点则且当前14点大于支付时间则需要推送
		ld = LocalDate.now(ZoneId.systemDefault());
		LocalDateTime toDayTime = ld.atTime(14, 0);
		time = Date.from(toDayTime.atZone(ZoneId.systemDefault()).toInstant()).getTime();
		if (System.currentTimeMillis() > time
				&& time > payTime.getTime()){
			return true;
		}

		return false;
	}

	@Override
	public CommonResult lockOrder(OrdersForbidRequest ordersForbidRequest) {
		OrdersForbid ordersForbid = new OrdersForbid();
		Admin admin = memberService.getAdmin();
		if(ordersForbidRequest.getStatus() == 0){
			if(StringUtils.isEmpty(ordersForbidRequest.getRemarks())){
				throw new ApiException("备注不能为空！");
			}else if(null == ordersForbidRequest.getType()){
				throw new ApiException("锁单类型不能为空！");
			}else if(null == ordersForbidRequest.getOrderInfoId()){
				throw new ApiException("子订单id不能为空！");
			}
		}
		ordersForbid.setRemarks(ordersForbidRequest.getRemarks());
		ordersForbid.setStatus(ordersForbidRequest.getStatus());
		//新增
		if(null == ordersForbidRequest.getId()){
			OrdersInfo ordersInfo = ordersInfoMapper.selectByPrimaryKey(ordersForbidRequest.getOrderInfoId());
			ordersForbid.setOrdersInfoId(ordersInfo.getId());
			ordersForbid.setOrderId(ordersInfo.getOrderId());
			if("6".equals(ordersInfo.getOrderinfoStatus()) && ordersForbidRequest.getType() == 1){
				throw new ApiException("订单正在售后，无法禁止售后");
			}
			ordersForbid.setForbidType(ordersForbidRequest.getType());
			ordersForbid.setCreateTime(new Date());
			ordersForbid.setOperatorId(admin.getId());
			try {
				//是否存在
				OrdersForbid oldEntity = new OrdersForbid();
				oldEntity.setOrdersInfoId(ordersForbidRequest.getOrderInfoId());
				oldEntity.setForbidType(ordersForbidRequest.getType());
				OrdersForbidResponse lockOrderInfo = ordersForbidMapper.getLockOrderInfo(oldEntity);
				if(lockOrderInfo != null){
					ordersForbid.setId(lockOrderInfo.getId());
					ordersForbidMapper.updateByPrimaryKeySelective(ordersForbid);
				}else {
					ordersForbidMapper.insert(ordersForbid);
				}
			} catch (Exception e) {
				throw new ApiException("数据已存在，请刷新数据后重试！");
			}
		}else {//修改
			ordersForbid.setId(ordersForbidRequest.getId());
			ordersForbid.setUpdateTime(new Date());
			ordersForbid.setUpdateId(admin.getId());
			if(ordersForbidRequest.getStatus() == 1){//解除锁定操作
				ordersForbid.setUnlockAdminId(admin.getId());
				ordersForbid.setUnlockMark(ordersForbidRequest.getUnlockMark());
				ordersForbid.setUnlockTime(new Date());
			}
			ordersForbidMapper.updateByPrimaryKeySelective(ordersForbid);
		}
		return CommonResult.success();
	}

	@Override
	public OrdersForbidResponse getLockOrderInfo(Integer id) {
		if(null == id){
			return null;
		}
		OrdersForbid ordersForbid = new OrdersForbid();
		ordersForbid.setId(id);
		OrdersForbidResponse lockOrderInfo = ordersForbidMapper.getLockOrderInfo(ordersForbid);
		return lockOrderInfo;
	}

	@Override
	public CommonPage<OrdersForbidResponse> getLockOrderInfoByPage(OrdersForbidPageRequest request) {
		PageHelper.startPage(request.getPageNum(),request.getPageSize());
//		request.setStatus(0);
		List<OrdersForbidResponse> lockOrderList = ordersForbidMapper.getLockOrderList(request);
		CommonPage<OrdersForbidResponse> ordersForbidResponseCommonPage = CommonPage.restPage(lockOrderList);
		return ordersForbidResponseCommonPage;
	}

	public static void main(String[] args) {
		//redis状态
		String orderInfoStatus = "5";
		OrdersInfo info = new OrdersInfo();
		info.setExpressNo("22");
		info.setExpressCompanyNo("22");
		//订单状态
		info.setOrderinfoStatus("6");
		if (StringUtils.isEmpty(orderInfoStatus) || "6".equals(orderInfoStatus) || "6".equals(info.getOrderinfoStatus())) {
			if ("6".equals(info.getOrderinfoStatus())) {
				if (!StringUtils.isEmpty(info.getExpressNo()) && !StringUtils.isEmpty(info.getExpressCompanyNo())) {
					orderInfoStatus = OrderStatusEnums.DELIVERY.getStatus();
				} else {
					orderInfoStatus = OrderStatusEnums.WAIT_DELIVERY.getStatus();
				}
			} else {
				orderInfoStatus = info.getOrderinfoStatus();
			}
		} else {
			orderInfoStatus = info.getOrderinfoStatus();
		}
		//redis保存原状态
		System.out.println("======需要更新的状态是=========" + orderInfoStatus);
	}

	@Override
	public boolean checkUserPhoneIsLimitRole() {
		boolean isLimitRole = false;
		try {
			String userId = UserUtil.getPrincipal();
			List<Role> role = adminService.getRoleByEmail(userId);
			log.info("====currentUserRoldId={}", role.toString());
			if (org.apache.commons.collections.CollectionUtils.isNotEmpty(role) && !com.alibaba.excel.util.StringUtils.isEmpty(limitUserPhoneRoleId)) {
				List<String> limitRoleIds = Arrays.asList(limitUserPhoneRoleId.split(","));
				if (limitRoleIds.contains(String.valueOf(role.get(0).getId()))) {
					isLimitRole = true;
				}
			}
		} catch (Exception e) {
			log.error("{}", e);
		}
		return isLimitRole;

	}
}
